|
1
2
|
const Mock = require("mockjs");
const { param2Obj } = require("./utils");
|
|
3
|
|
|
4
5
|
const user = require("./user");
const table = require("./table");
|
|
6
|
|
|
7
|
const mocks = [...user, ...table];
|
|
8
9
10
11
12
13
14
|
// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
function mockXHR() {
// mock patch
// https://github.com/nuysoft/Mock/issues/300
|
|
15
16
|
Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send;
Mock.XHR.prototype.send = function () {
|
|
17
|
if (this.custom.xhr) {
|
|
18
|
this.custom.xhr.withCredentials = this.withCredentials || false;
|
|
19
20
|
if (this.responseType) {
|
|
21
|
this.custom.xhr.responseType = this.responseType;
|
|
22
23
|
}
}
|
|
24
25
|
this.proxy_send(...arguments);
};
|
|
26
27
|
function XHR2ExpressReqWrap(respond) {
|
|
28
29
|
return function (options) {
let result = null;
|
|
30
|
if (respond instanceof Function) {
|
|
31
|
const { body, type, url } = options;
|
|
32
33
34
35
|
// https://expressjs.com/en/4x/api.html#req
result = respond({
method: type,
body: JSON.parse(body),
|
|
36
37
|
query: param2Obj(url),
});
|
|
38
|
} else {
|
|
39
|
result = respond;
|
|
40
|
}
|
|
41
42
|
return Mock.mock(result);
};
|
|
43
44
45
|
}
for (const i of mocks) {
|
|
46
47
48
49
50
|
Mock.mock(
new RegExp(i.url),
i.type || "get",
XHR2ExpressReqWrap(i.response)
);
|
|
51
52
53
54
55
|
}
}
module.exports = {
mocks,
|
|
56
57
|
mockXHR,
};
|