This commit is contained in:
Pan 2019-04-08 10:57:27 +08:00
parent 8aa8e357d9
commit 85cfbd6bfc
3 changed files with 23 additions and 23 deletions

View File

@ -1,11 +1,23 @@
import Mock from 'mockjs'
import mocks from './mocks'
import { param2Obj } from '../src/utils'
export const MOCK_API_BASE = '/mock'
import user from './user'
import role from './role'
import article from './article'
import search from './remoteSearch'
const mocks = [
...user,
...role,
...article,
...search
]
// 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).
export function mockXHR() {
// 修复在使用 MockJS 情况下,设置 withCredentials = true且未被拦截的跨域请求丢失 Cookies 的问题
// mock patch
// https://github.com/nuysoft/Mock/issues/300
Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
Mock.XHR.prototype.send = function() {
@ -42,9 +54,10 @@ export function mockXHR() {
}
}
// for mock server
const responseFake = (url, type, respond) => {
return {
url: new RegExp(`${MOCK_API_BASE}${url}`),
url: new RegExp(`/mock${url}`),
type: type || 'get',
response(req, res) {
res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))

View File

@ -3,19 +3,18 @@ const bodyParser = require('body-parser')
const chalk = require('chalk')
function registerRoutes(app) {
const { default: mocks, MOCK_API_BASE } = require('./index.js')
const { default: mocks } = require('./index.js')
for (const mock of mocks) {
app[mock.type](mock.url, mock.response)
}
return {
mockRoutesLength: Object.keys(mocks).length,
MOCK_API_BASE: MOCK_API_BASE
mockRoutesLength: Object.keys(mocks).length
}
}
function unregisterRoutes(MOCK_API_BASE) {
function unregisterRoutes() {
Object.keys(require.cache).forEach(i => {
if (i.includes(MOCK_API_BASE)) {
if (i.includes('/mock')) {
delete require.cache[require.resolve(i)]
}
})
@ -54,7 +53,7 @@ module.exports = app => {
extended: true
}))
const { mockRoutesLength, MOCK_API_BASE } = registerRoutes(app)
const { mockRoutesLength } = registerRoutes(app)
// watch files, hot reload mock server
chokidar.watch(('./mock'), {
@ -70,7 +69,7 @@ module.exports = app => {
app._router.stack.splice(index, mockRoutesLength)
// clear routes cache
unregisterRoutes(MOCK_API_BASE)
unregisterRoutes()
registerRoutes(app)

View File

@ -1,12 +0,0 @@
import user from './user'
import role from './role'
import article from './article'
import search from './remoteSearch'
export default [
...user,
...role,
...article,
...search
]