mock-server.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const chokidar = require('chokidar')
  2. const bodyParser = require('body-parser')
  3. const chalk = require('chalk')
  4. const path = require('path')
  5. const Mock = require('mockjs')
  6. const mockDir = path.join(process.cwd(), 'mock')
  7. function registerRoutes(app) {
  8. let mockLastIndex
  9. const { default: mocks } = require('./index.js')
  10. const mocksForServer = mocks.map(route => {
  11. return responseFake(route.url, route.type, route.response)
  12. })
  13. for (const mock of mocksForServer) {
  14. app[mock.type](mock.url, mock.response)
  15. mockLastIndex = app._router.stack.length
  16. }
  17. const mockRoutesLength = Object.keys(mocksForServer).length
  18. return {
  19. mockRoutesLength: mockRoutesLength,
  20. mockStartIndex: mockLastIndex - mockRoutesLength
  21. }
  22. }
  23. function unregisterRoutes() {
  24. Object.keys(require.cache).forEach(i => {
  25. if (i.includes(mockDir)) {
  26. delete require.cache[require.resolve(i)]
  27. }
  28. })
  29. }
  30. // for mock server
  31. const responseFake = (url, type, respond) => {
  32. return {
  33. url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
  34. type: type || 'get',
  35. response(req, res) {
  36. console.log('request invoke:' + req.path)
  37. res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
  38. }
  39. }
  40. }
  41. module.exports = app => {
  42. // es6 polyfill
  43. require('@babel/register')
  44. // parse app.body
  45. // https://expressjs.com/en/4x/api.html#req.body
  46. app.use(bodyParser.json())
  47. app.use(bodyParser.urlencoded({
  48. extended: true
  49. }))
  50. const mockRoutes = registerRoutes(app)
  51. var mockRoutesLength = mockRoutes.mockRoutesLength
  52. var mockStartIndex = mockRoutes.mockStartIndex
  53. // watch files, hot reload mock server
  54. chokidar.watch(mockDir, {
  55. ignored: /mock-server/,
  56. ignoreInitial: true
  57. }).on('all', (event, path) => {
  58. if (event === 'change' || event === 'add') {
  59. try {
  60. // remove mock routes stack
  61. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  62. // clear routes cache
  63. unregisterRoutes()
  64. const mockRoutes = registerRoutes(app)
  65. mockRoutesLength = mockRoutes.mockRoutesLength
  66. mockStartIndex = mockRoutes.mockStartIndex
  67. console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
  68. } catch (error) {
  69. console.log(chalk.redBright(error))
  70. }
  71. }
  72. })
  73. }