Skip to content

Commit d6816c5

Browse files
authored
perf[Mock]: set responseFake to mock-server.js(PanJiaChen#2966)
* modify 把mock/index.js中与mock-server相关的代码转移到mock-server.js中去,实现两则功能分割
1 parent 6850312 commit d6816c5

File tree

2 files changed

+19
-17
lines changed

2 files changed

+19
-17
lines changed

mock/index.js

+1-15
Original file line numberDiff line numberDiff line change
@@ -54,18 +54,4 @@ export function mockXHR() {
5454
}
5555
}
5656

57-
// for mock server
58-
const responseFake = (url, type, respond) => {
59-
return {
60-
url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
61-
type: type || 'get',
62-
response(req, res) {
63-
console.log('request invoke:' + req.path)
64-
res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
65-
}
66-
}
67-
}
68-
69-
export default mocks.map(route => {
70-
return responseFake(route.url, route.type, route.response)
71-
})
57+
export default mocks

mock/mock-server.js

+18-2
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,21 @@ const chokidar = require('chokidar')
22
const bodyParser = require('body-parser')
33
const chalk = require('chalk')
44
const path = require('path')
5+
const Mock = require('mockjs')
56

67
const mockDir = path.join(process.cwd(), 'mock')
78

89
function registerRoutes(app) {
910
let mockLastIndex
1011
const { default: mocks } = require('./index.js')
11-
for (const mock of mocks) {
12+
const mocksForServer = mocks.map(route => {
13+
return responseFake(route.url, route.type, route.response)
14+
})
15+
for (const mock of mocksForServer) {
1216
app[mock.type](mock.url, mock.response)
1317
mockLastIndex = app._router.stack.length
1418
}
15-
const mockRoutesLength = Object.keys(mocks).length
19+
const mockRoutesLength = Object.keys(mocksForServer).length
1620
return {
1721
mockRoutesLength: mockRoutesLength,
1822
mockStartIndex: mockLastIndex - mockRoutesLength
@@ -27,6 +31,18 @@ function unregisterRoutes() {
2731
})
2832
}
2933

34+
// for mock server
35+
const responseFake = (url, type, respond) => {
36+
return {
37+
url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
38+
type: type || 'get',
39+
response(req, res) {
40+
console.log('request invoke:' + req.path)
41+
res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
42+
}
43+
}
44+
}
45+
3046
module.exports = app => {
3147
// es6 polyfill
3248
require('@babel/register')

0 commit comments

Comments
 (0)