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
const { chokidar, signale, createDebug } = require('@umijs/utils');
const utils = require('./util');
const debug = createDebug('preset-build-in:mock:createMiddleware');
function createMiddleware(opts) {
const { mockData, mockWatcherPaths, updateMockData } = opts;
let data = mockData;
const errors = [];
debug('mockWatcherPaths', mockWatcherPaths);
const watcher = chokidar.watch(mockWatcherPaths, {
ignoreInitial: true,
});
watcher
.on('ready', () => debug('Initial scan complete. Ready for changes'))
.on('all', async (event, file) => {
debug(`[${event}] ${file}, reload mock data`);
errors.splice(0, errors.length);
utils.cleanRequireCache(mockWatcherPaths);
// eslint-disable-next-line no-const-assign
data = await updateMockData().mockData;
if (!errors.length) {
signale.success(`Mock files parse success`);
}
});
process.once('SIGINT', async () => {
await watcher.close();
});
return {
middleware: (req, res, next) => {
const match = data && utils.matchMock(req, data);
if (match) {
return match.handler(req, res, next);
}
return next();
},
};
}
module.exports = createMiddleware