-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.js
68 lines (52 loc) · 1.4 KB
/
mock.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
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const http = require('http');
const log = require('./utils/log');
const file = require('fs');
const logger = require('./middlewares/logger');
const delay = require('./middlewares/delay');
/**
* @param {String} msg
*/
const throwAnError = msg => {
log.error(log.getMark(), msg);
process.exit(1);
};
module.exports = (options = {}) => {
if (!options.routes) {
throwAnError('Routes should be provided');
}
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.all('*', logger);
app.all('*', delay);
let appRoutes;
switch (typeof options.routes) {
case 'string':
if (!file.existsSync(options.routes)) {
throwAnError('The file containing an additional routes should exist');
}
appRoutes = require(options.routes);
break;
case 'function':
appRoutes = options.routes;
break;
default:
throwAnError('Routes should be a string path to file or function representing module exports');
}
// register additional routes
appRoutes(app, options);
const port = options.port || 1234;
// init server
http.createServer(app).listen(port, () => {
log.info(
log.getMark(),
`Server is established on http://localhost:${port}`
);
});
};