forked from temrdm/gulp-rest-emulator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
111 lines (88 loc) · 2.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
var es = require('event-stream');
var restEmulator = require('rest-emulator');
var express = require('express');
var bodyParser = require('body-parser');
var https = require('https');
var gutil = require('gulp-util');
var _ = require('lodash');
var serveStatic = require('serve-static');
var path = require('path');
var cors = require('cors');
var server;
exports = module.exports = gulpRestEmulator;
function gulpRestEmulator(options) {
var app = express();
var config = [];
var restInstance;
options = getNormalizeOptions(options);
if (options.useJsonBody !== false) {
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
}
return es.through(read, end);
function read(file) {
var stream = this;
if (require.cache[file.path]) {
delete require.cache[file.path];
}
try {
config.push(require(file.path));
} catch (error) {
throw new gutil.PluginError('gulp-rest-emulator', 'Cannot read mock module ' + file.path);
}
return stream.emit('data', file);
}
function end() {
var stream = this;
if (_.keys(options.headers).length) {
app.use(function (req, res, next) {
res.set(options.headers);
next();
})
}
if (options.corsEnable) {
app.use(cors(options.corsOptions));
}
if (restInstance) {
restInstance.updateConfing(config);
} else {
restInstance = restEmulator(config, options.restOptions || {});
app.use(restInstance.middleware);
}
_.each(options.root, serve);
if (options.rewriteNotFound) {
var indexFile = path.resolve('.', options.rewriteTemplate);
app.get('*', function (req, res) {
return res.sendFile(indexFile);
});
}
stream.emit('end');
if (!server) {
server = (options.httpsEnable ? https.createServer(options.httpsOptions, app).listen(options.port) : app.listen(options.port));
}
return server;
}
function serve(root) {
app.use(serveStatic(root));
}
}
function getNormalizeOptions(options) {
var defaults = {
port: 8000,
root: ['./'],
rewriteNotFound: false,
rewriteTemplate: 'index.html',
corsEnable: false,
corsOptions: {},
headers: {},
httpsEnable: false,
httpsOptions: {},
useJsonBody: false
};
if (!_.isPlainObject(options)) {
return defaults;
}
return _.defaults(options, defaults);
}