-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (52 loc) · 1.58 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
let path = require("path");
let express = require("express");
let cors = require("cors");
let { createProxyMiddleware } = require("http-proxy-middleware");
let fsMock = require("./src/fs-mock.js");
function init(app, config) {
app.get("/", (req, res) => {
res.send("Mock Service!");
});
let proxy = config.proxy || {};
let filter = function (pathname, req) {
let mockApiPath = fsMock.generateApiPath(config.mock);
if (mockApiPath.includes(fsMock.generateApi(req.method, pathname))) {
return false;
}
if (pathname === "/") return false;
return true;
};
for (let key in proxy) {
if (Object.hasOwnProperty.call(proxy, key)) {
app.use(key, createProxyMiddleware(filter, proxy[key]));
}
}
app.all("*", function (req, res) {
let mockFileName = fsMock.generateApi(req.method, req.path);
try {
let mockFilePath = path.join(config.mock, `./${mockFileName}.js`);
delete require.cache[mockFilePath];
let data = require(mockFilePath);
res.status(data.httpStatus || 200).send(data.response);
} catch (error) {
console.log(error);
res.send("response exception");
}
});
}
module.exports = {
start: function (config) {
if (!config) {
throw new Error("must contain the confing parameter");
}
if (!config.mock || !config.port || !config.proxy) {
throw new Error("wrong parameter");
}
let app = express();
app.use(cors());
init(app, config);
app.listen(config.port, () => {
console.log(`mock service listening on port ${config.port}`);
});
},
};