-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathcreateMockServer.ts
244 lines (211 loc) · 6.38 KB
/
createMockServer.ts
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import type { ViteMockOptions, MockMethod } from './types';
import { existsSync } from 'fs';
import { join } from 'path';
import chokidar from 'chokidar';
import chalk from 'chalk';
import url from 'url';
import fg from 'fast-glob';
import Mock from 'mockjs';
import { rollup } from 'rollup';
import esbuildPlugin from 'rollup-plugin-esbuild';
import { pathToRegexp, match } from 'path-to-regexp';
import { isArray, isFunction, sleep, isRegExp, loadConfigFromBundledFile } from './utils';
import createServer, { NextHandleFunction } from 'connect';
const pathResolve = require('@rollup/plugin-node-resolve');
export let mockData: MockMethod[] = [];
export async function createMockServer(
opt: ViteMockOptions = { mockPath: 'mock', configPath: 'vite.mock.config' }
) {
opt = {
mockPath: 'mock',
watchFiles: true,
supportTs: true,
configPath: 'vite.mock.config.ts',
logger: true,
...opt,
};
if (mockData.length > 0) return;
mockData = await getMockConfig(opt);
const { watchFiles = true } = opt;
if (watchFiles) {
const watch = await createWatch(opt);
watch && watch();
}
}
// request match
export async function requestMiddle(opt: ViteMockOptions) {
const { logger = true } = opt;
const middleware: NextHandleFunction = async (req, res, next) => {
let queryParams: {
query?: {
[key: string]: any;
};
pathname?: string | null;
} = {};
const isGet = req.method && req.method.toUpperCase() === 'GET';
if (isGet && req.url) {
queryParams = url.parse(req.url, true);
}
const reqUrl = isGet ? queryParams.pathname : req.url;
const matchReq = mockData.find((item) => {
if (item.method && item.method.toUpperCase() !== req.method) return false;
if (!reqUrl) return false;
return pathToRegexp(item.url).test(reqUrl);
});
if (matchReq) {
const { response, timeout, statusCode, url } = matchReq;
if (timeout) {
await sleep(timeout);
}
const urlMatch = match(url, { decode: decodeURIComponent });
let query = queryParams.query;
if (reqUrl && JSON.stringify(query) == '{}') {
query = (urlMatch(reqUrl) as any).params || {};
}
const body = (await parseJson(req)) as Record<string, any>;
const mockRes = isFunction(response) ? response({ body, query }) : response;
logger && loggerOutput('request invoke', req.url!);
res.setHeader('Content-Type', 'application/json');
res.statusCode = statusCode || 200;
res.end(JSON.stringify(Mock.mock(mockRes)));
return;
}
next();
};
return middleware;
}
// create watch mock
function createWatch(opt: ViteMockOptions) {
const { configPath, logger } = opt;
const { absConfigPath, absMockPath } = getPath(opt);
if (process.env.VITE_DISABLED_WATCH_MOCK === 'true') return;
const watchDir = [];
const exitsConfigPath = existsSync(absConfigPath);
exitsConfigPath && configPath ? watchDir.push(absConfigPath) : watchDir.push(absMockPath);
const watcher = chokidar.watch(watchDir, {
ignoreInitial: true,
});
const watch = () => {
watcher.on('all', async (event, file) => {
logger && loggerOutput(`mock file ${event}`, file);
mockData = await getMockConfig(opt);
});
};
return watch;
}
// clear cache
function cleanRequireCache(opt: ViteMockOptions) {
const { absConfigPath, absMockPath } = getPath(opt);
Object.keys(require.cache).forEach((file) => {
if (file === absConfigPath || file.indexOf(absMockPath) > -1) {
delete require.cache[file];
}
});
}
function parseJson(req: createServer.IncomingMessage) {
return new Promise((resolve) => {
let body = '';
let jsonStr = '';
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
try {
jsonStr = JSON.parse(body);
} catch (err) {
jsonStr = '';
}
resolve(jsonStr);
return;
});
});
}
// load mock .ts files and watch
async function getMockConfig(opt: ViteMockOptions) {
cleanRequireCache(opt);
const { absConfigPath, absMockPath } = getPath(opt);
const { ignore, configPath, supportTs, logger } = opt;
let ret: any[] = [];
if (configPath && existsSync(absConfigPath)) {
logger && loggerOutput(`load mock data from`, absConfigPath);
ret = await resolveModule(absConfigPath);
} else {
const mockFiles = fg
.sync(`**/*.${supportTs ? 'ts' : 'js'}`, {
cwd: absMockPath,
})
.filter((item) => {
if (!ignore) {
return true;
}
if (isFunction(ignore)) {
return ignore(item);
}
if (isRegExp(ignore)) {
return !ignore.test(item);
}
return true;
});
try {
ret = [];
for (let index = 0; index < mockFiles.length; index++) {
const mockFile = mockFiles[index];
const resultModule = await resolveModule(join(absMockPath, mockFile));
let mod = resultModule;
if (!isArray(mod)) {
mod = [mod];
}
ret = [...ret, ...mod];
}
} catch (error) {
loggerOutput(`mock reload error`, error);
ret = [];
}
}
return ret;
}
// Inspired by vite
// support mock .ts files
async function resolveModule(path: string): Promise<any> {
// use node-resolve to support .ts files
const nodeResolve = pathResolve.nodeResolve({
extensions: ['.js', '.ts'],
});
const bundle = await rollup({
input: path,
treeshake: false,
plugins: [
esbuildPlugin({
include: /\.[jt]sx?$/,
exclude: /node_modules/,
sourceMap: false,
}),
nodeResolve,
],
});
const {
output: [{ code }],
} = await bundle.generate({
exports: 'named',
format: 'cjs',
});
return await loadConfigFromBundledFile(path, code);
}
// get custom config file path and mock dir path
function getPath(opt: ViteMockOptions) {
const { mockPath, configPath } = opt;
const cwd = process.cwd();
const absMockPath = join(cwd, mockPath || '');
const absConfigPath = join(cwd, configPath || '');
return {
absMockPath,
absConfigPath,
};
}
function loggerOutput(title: string, msg: string, type: 'info' | 'error' = 'info') {
const tag =
type === 'info' ? chalk.cyan.bold(`[vite:mock]`) : chalk.red.bold(`[vite:mock-server]`);
return console.log(
`${chalk.dim(new Date().toLocaleTimeString())} ${tag} ${chalk.green(title)} ${chalk.dim(msg)}`
);
}