From d0518bce5b1e5fc07c4458ef2cc13110e0357a78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=BD=98=E5=98=89=E6=99=A8?= Date: Thu, 4 Jun 2020 21:14:26 +0800 Subject: [PATCH] perf[Mock]: set responseFake to mock-server.js https://github.com/PanJiaChen/vue-element-admin/pull/2966 --- mock/index.js | 16 +--------------- mock/mock-server.js | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/mock/index.js b/mock/index.js index 90e2ffe..aca99f4 100644 --- a/mock/index.js +++ b/mock/index.js @@ -50,18 +50,4 @@ export function mockXHR() { } } -// for mock server -const responseFake = (url, type, respond) => { - return { - url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`), - type: type || 'get', - response(req, res) { - console.log('request invoke:' + req.path) - res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond)) - } - } -} - -export default mocks.map(route => { - return responseFake(route.url, route.type, route.response) -}) +export default mocks diff --git a/mock/mock-server.js b/mock/mock-server.js index 4c4cb2a..806fdac 100644 --- a/mock/mock-server.js +++ b/mock/mock-server.js @@ -2,17 +2,21 @@ const chokidar = require('chokidar') const bodyParser = require('body-parser') const chalk = require('chalk') const path = require('path') +const Mock = require('mockjs') const mockDir = path.join(process.cwd(), 'mock') function registerRoutes(app) { let mockLastIndex const { default: mocks } = require('./index.js') - for (const mock of mocks) { + const mocksForServer = mocks.map(route => { + return responseFake(route.url, route.type, route.response) + }) + for (const mock of mocksForServer) { app[mock.type](mock.url, mock.response) mockLastIndex = app._router.stack.length } - const mockRoutesLength = Object.keys(mocks).length + const mockRoutesLength = Object.keys(mocksForServer).length return { mockRoutesLength: mockRoutesLength, mockStartIndex: mockLastIndex - mockRoutesLength @@ -27,6 +31,18 @@ function unregisterRoutes() { }) } +// for mock server +const responseFake = (url, type, respond) => { + return { + url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`), + type: type || 'get', + response(req, res) { + console.log('request invoke:' + req.path) + res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond)) + } + } +} + module.exports = app => { // es6 polyfill require('@babel/register')