forked from temrdm/gulp-rest-emulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (51 loc) · 1.52 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
var es = require('event-stream');
var restEmulator = require('rest-emulator');
var express = require('express');
var gutil = require('gulp-util');
var _ = require('lodash');
var serveStatic = require('serve-static');
var path = require('path');
exports = module.exports = gulpRestEmulator;
function gulpRestEmulator(options) {
var app = express();
var config = [];
options = getNormalizeOptions(options);
return es.through(read, end);
function read(file) {
var stream = this;
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;
app.use(restEmulator(config));
_.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');
return app.listen(options.port);
}
function serve(root) {
app.use(serveStatic(root));
}
}
function getNormalizeOptions(options) {
var defaults = {
port: 8000,
root: ['./'],
rewriteNotFound: false,
rewriteTemplate: 'index.html'
};
if (!_.isPlainObject(options)) {
return defaults;
}
return _.defaults(options, defaults);
}