-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.mock.js
85 lines (76 loc) · 2.1 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// const registerBabel = require('./mock/registerBabel')
// const cwd = process.cwd()
// const babel = {
// presets: [
// '@vue/app'
// ]
// }
// registerBabel(babel, {
// cwd,
// configOnly: true,
// })
const url = require('url')
const path = require('path')
const { join, resolve } = require('path')
const proxy = require('express-http-proxy')
const mockPath = resolve(__dirname, 'mockData.js')
const config = require(mockPath)
// console.log(config, 'mock config')
function parseKey(key) {
let method = 'get';
let path = key;
if (key.indexOf(' ') > -1) {
const splited = key.split(' ');
method = splited[0].toLowerCase();
path = splited[1];
}
return {
method,
path
};
}
function winPath (path) {
return path.replace(/\\/g, '/');
}
function createMockHandler(method, path, value) {
return function mockHandler(...args) {
const res = args[1];
if (typeof value === 'function') {
value(...args);
} else {
res.json(value);
}
};
}
function createProxy(method, path, target) {
return proxy(target, {
filter(req) {
return method ? req.method.toLowerCase() === method.toLowerCase() : true;
},
forwardPath(req) {
let matchPath = req.originalUrl;
const matches = matchPath.match(path);
if (matches.length > 1) {
matchPath = matches[1];
}
return winPath(join(url.parse(target).path, matchPath));
},
});
}
module.exports = function (app) {
Object.keys(config).forEach(key => {
const keyParsed = parseKey(key);
if (typeof config[key] === 'string') {
let { path } = keyParsed;
if (/\(.+\)/.test(path)) {
path = new RegExp(`^${path}$`);
}
app.use(path, createProxy(keyParsed.method, path, config[key]));
} else {
app[keyParsed.method](
keyParsed.path,
createMockHandler(keyParsed.method, keyParsed.path, config[key]),
);
}
})
}