-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (86 loc) · 2.62 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
#!/usr/bin/env node
var express = require('express');
var restEmulator = require('rest-emulator');
var recursive = require('recursive-readdir');
var path = require('path');
var fs = require('fs');
var serveStatic = require('serve-static');
var app = express();
var cors = require('cors');
var _ = require('lodash');
var reloadRequire = require('require-nocache')(module);
const defaultOptions = {
port: 3000,
dir: '/mocks',
root: ['./'],
rewriteNotFound: false,
corsEnable: true,
rewriteTemplate: 'index.html',
headers: {}
};
const options = getOptions();
function pick(chooses) {
return _.sample(chooses);
}
function jsonOnly(file, stats) {
return path.extname(file) === '.json';
}
function getJSON(filename) {
return JSON.parse(fs.readFileSync(filename, 'utf8'));
}
function jsOnly(file, stats) {
return path.extname(file) === '.js';
}
function getJs(filename) {
return reloadRequire(filename);
}
function getOptions() {
if (process.argv.length > 2) {
const passedOptions = JSON.parse(fs.readFileSync(process.argv[2]));
return Object.assign(defaultOptions, passedOptions);
}
return defaultOptions;
}
function setHeader(resources) {
_.each(resources, function(resource, key) {
if (resource.data !== undefined) {
resource.headers = options.headers;
} else {
_.each(resource, function(httpMethod, key) {
httpMethod.headers = options.headers;
});
}
});
}
function getConfigs(cb) {
recursive(process.cwd() + options.dir, function(err, filenames) {
if (err) {
throw `Failed to read the files in ${process.cwd() + options.dir}, error says: ${err}`;
}
const jsonConfigs = filenames.filter(jsonOnly).map(getJSON);
const jsConfigs = filenames.filter(jsOnly).map(getJs);
const configs = jsConfigs.concat(jsonConfigs);
if (Object.keys(options.headers).length) {
configs.forEach(setHeader);
}
cb(configs);
});
}
function startServer() {
if (options.corsEnable) {
app.use(cors(options.corsOptions));
}
app.use(function(req, res, next){
getConfigs((configs) => restEmulator(configs).middleware(req,res,next));
});
options.root.forEach((dir) => app.use(serveStatic(dir)));
if (options.rewriteNotFound) {
var indexFile = path.resolve('.', options.rewriteTemplate);
app.get('*', function(req, res) {
return res.sendFile(indexFile);
});
}
app.listen(options.port);
console.log(`Started the rest server on ${options.port}`);
}
startServer();