|
1
2
3
4
5
|
const chokidar = require("chokidar");
const bodyParser = require("body-parser");
const chalk = require("chalk");
const path = require("path");
const Mock = require("mockjs");
|
|
6
|
|
|
7
|
const mockDir = path.join(process.cwd(), "mock");
|
|
8
9
|
function registerRoutes(app) {
|
|
10
11
12
13
14
|
let mockLastIndex;
const { mocks } = require("./index.js");
const mocksForServer = mocks.map((route) => {
return responseFake(route.url, route.type, route.response);
});
|
|
15
|
for (const mock of mocksForServer) {
|
|
16
17
|
app[mock.type](mock.url, mock.response);
mockLastIndex = app._router.stack.length;
|
|
18
|
}
|
|
19
|
const mockRoutesLength = Object.keys(mocksForServer).length;
|
|
20
21
|
return {
mockRoutesLength: mockRoutesLength,
|
|
22
23
|
mockStartIndex: mockLastIndex - mockRoutesLength,
};
|
|
24
25
26
|
}
function unregisterRoutes() {
|
|
27
|
Object.keys(require.cache).forEach((i) => {
|
|
28
|
if (i.includes(mockDir)) {
|
|
29
|
delete require.cache[require.resolve(i)];
|
|
30
|
}
|
|
31
|
});
|
|
32
33
34
35
36
37
|
}
// for mock server
const responseFake = (url, type, respond) => {
return {
url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
|
|
38
|
type: type || "get",
|
|
39
|
response(req, res) {
|
|
40
41
42
43
44
45
46
|
console.log("request invoke:" + req.path);
res.json(
Mock.mock(respond instanceof Function ? respond(req, res) : respond)
);
},
};
};
|
|
47
|
|
|
48
|
module.exports = (app) => {
|
|
49
50
|
// parse app.body
// https://expressjs.com/en/4x/api.html#req.body
|
|
51
52
53
54
55
56
|
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
})
);
|
|
57
|
|
|
58
59
60
|
const mockRoutes = registerRoutes(app);
var mockRoutesLength = mockRoutes.mockRoutesLength;
var mockStartIndex = mockRoutes.mockStartIndex;
|
|
61
62
|
// watch files, hot reload mock server
|
|
63
64
65
66
67
68
69
70
71
72
|
chokidar
.watch(mockDir, {
ignored: /mock-server/,
ignoreInitial: true,
})
.on("all", (event, path) => {
if (event === "change" || event === "add") {
try {
// remove mock routes stack
app._router.stack.splice(mockStartIndex, mockRoutesLength);
|
|
73
|
|
|
74
75
|
// clear routes cache
unregisterRoutes();
|
|
76
|
|
|
77
78
79
|
const mockRoutes = registerRoutes(app);
mockRoutesLength = mockRoutes.mockRoutesLength;
mockStartIndex = mockRoutes.mockStartIndex;
|
|
80
|
|
|
81
82
83
84
85
86
87
88
|
console.log(
chalk.magentaBright(
`\n > Mock Server hot reload success! changed ${path}`
)
);
} catch (error) {
console.log(chalk.redBright(error));
}
|
|
89
|
}
|
|
90
91
|
});
};
|