2019-04-08 03:01:24 +00:00
|
|
|
const chokidar = require('chokidar')
|
|
|
|
const bodyParser = require('body-parser')
|
|
|
|
const chalk = require('chalk')
|
2019-04-18 10:36:20 +00:00
|
|
|
const path = require('path')
|
|
|
|
|
|
|
|
const mockDir = path.join(process.cwd(), 'mock')
|
2019-04-08 03:01:24 +00:00
|
|
|
|
|
|
|
function registerRoutes(app) {
|
2019-04-11 02:00:21 +00:00
|
|
|
let mockLastIndex
|
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-11 02:00:21 +00:00
|
|
|
mockLastIndex = 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,
|
2019-04-11 02:00:21 +00:00
|
|
|
mockStartIndex: mockLastIndex - mockRoutesLength
|
2019-04-08 03:01:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function unregisterRoutes() {
|
|
|
|
Object.keys(require.cache).forEach(i => {
|
2019-04-18 10:36:20 +00:00
|
|
|
if (i.includes(mockDir)) {
|
2019-04-08 03:01:24 +00:00
|
|
|
delete require.cache[require.resolve(i)]
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = app => {
|
|
|
|
// es6 polyfill
|
|
|
|
require('@babel/register')
|
|
|
|
|
|
|
|
// parse app.body
|
2019-04-11 01:42:44 +00:00
|
|
|
// https://expressjs.com/en/4x/api.html#req.body
|
2019-04-08 03:01:24 +00:00
|
|
|
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
|
2019-04-18 10:36:20 +00:00
|
|
|
chokidar.watch(mockDir, {
|
|
|
|
ignored: /mock-server/,
|
2019-04-08 03:01:24 +00:00
|
|
|
ignoreInitial: true
|
|
|
|
}).on('all', (event, path) => {
|
|
|
|
if (event === 'change' || event === 'add') {
|
2019-04-28 09:53:07 +00:00
|
|
|
try {
|
|
|
|
// remove mock routes stack
|
|
|
|
app._router.stack.splice(mockStartIndex, mockRoutesLength)
|
2019-04-08 03:01:24 +00:00
|
|
|
|
2019-04-28 09:53:07 +00:00
|
|
|
// clear routes cache
|
|
|
|
unregisterRoutes()
|
2019-04-08 03:01:24 +00:00
|
|
|
|
2019-04-28 09:53:07 +00:00
|
|
|
const mockRoutes = registerRoutes(app)
|
|
|
|
mockRoutesLength = mockRoutes.mockRoutesLength
|
|
|
|
mockStartIndex = mockRoutes.mockStartIndex
|
2019-04-08 03:01:24 +00:00
|
|
|
|
2019-04-28 09:53:07 +00:00
|
|
|
console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
|
|
|
|
} catch (error) {
|
|
|
|
console.log(chalk.redBright(error))
|
|
|
|
}
|
2019-04-08 03:01:24 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|