2019-04-08 03:01:24 +00:00
|
|
|
const chokidar = require('chokidar')
|
|
|
|
const bodyParser = require('body-parser')
|
|
|
|
const chalk = require('chalk')
|
|
|
|
|
|
|
|
function registerRoutes(app) {
|
2019-04-09 06:25:14 +00:00
|
|
|
let mockStartIndex
|
2019-04-08 03:01:24 +00:00
|
|
|
const { default: mocks } = require('./index.js')
|
|
|
|
for (const mock of mocks) {
|
|
|
|
app[mock.type](mock.url, mock.response)
|
2019-04-09 06:25:14 +00:00
|
|
|
mockStartIndex = app._router.stack.length
|
2019-04-08 03:01:24 +00:00
|
|
|
}
|
2019-04-09 06:25:14 +00:00
|
|
|
const mockRoutesLength = Object.keys(mocks).length
|
2019-04-08 03:01:24 +00:00
|
|
|
return {
|
2019-04-09 06:25:14 +00:00
|
|
|
mockRoutesLength: mockRoutesLength,
|
|
|
|
mockStartIndex: mockStartIndex - mockRoutesLength
|
2019-04-08 03:01:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function unregisterRoutes() {
|
|
|
|
Object.keys(require.cache).forEach(i => {
|
|
|
|
if (i.includes('/mock')) {
|
|
|
|
delete require.cache[require.resolve(i)]
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = app => {
|
|
|
|
// es6 polyfill
|
|
|
|
require('@babel/register')
|
|
|
|
|
|
|
|
// parse app.body
|
|
|
|
// http://expressjs.com/en/4x/api.html#req.body
|
|
|
|
app.use(bodyParser.json())
|
|
|
|
app.use(bodyParser.urlencoded({
|
|
|
|
extended: true
|
|
|
|
}))
|
|
|
|
|
2019-04-09 06:25:14 +00:00
|
|
|
const mockRoutes = registerRoutes(app)
|
|
|
|
var mockRoutesLength = mockRoutes.mockRoutesLength
|
|
|
|
var mockStartIndex = mockRoutes.mockStartIndex
|
2019-04-08 03:01:24 +00:00
|
|
|
|
|
|
|
// watch files, hot reload mock server
|
|
|
|
chokidar.watch(('./mock'), {
|
|
|
|
ignored: 'mock/mock-server.js',
|
|
|
|
persistent: true,
|
|
|
|
ignoreInitial: true
|
|
|
|
}).on('all', (event, path) => {
|
|
|
|
if (event === 'change' || event === 'add') {
|
|
|
|
// remove mock routes stack
|
2019-04-09 06:25:14 +00:00
|
|
|
app._router.stack.splice(mockStartIndex, mockRoutesLength)
|
2019-04-08 03:01:24 +00:00
|
|
|
|
|
|
|
// clear routes cache
|
|
|
|
unregisterRoutes()
|
|
|
|
|
2019-04-09 06:25:14 +00:00
|
|
|
const mockRoutes = registerRoutes(app)
|
|
|
|
mockRoutesLength = mockRoutes.mockRoutesLength
|
|
|
|
mockStartIndex = mockRoutes.mockStartIndex
|
2019-04-08 03:01:24 +00:00
|
|
|
|
|
|
|
console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|