mock-server.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 { 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. // parse app.body
  43. // https://expressjs.com/en/4x/api.html#req.body
  44. app.use(bodyParser.json())
  45. app.use(bodyParser.urlencoded({
  46. extended: true
  47. }))
  48. const mockRoutes = registerRoutes(app)
  49. var mockRoutesLength = mockRoutes.mockRoutesLength
  50. var mockStartIndex = mockRoutes.mockStartIndex
  51. // watch files, hot reload mock server
  52. chokidar.watch(mockDir, {
  53. ignored: /mock-server/,
  54. ignoreInitial: true
  55. }).on('all', (event, path) => {
  56. if (event === 'change' || event === 'add') {
  57. try {
  58. // remove mock routes stack
  59. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  60. // clear routes cache
  61. unregisterRoutes()
  62. const mockRoutes = registerRoutes(app)
  63. mockRoutesLength = mockRoutes.mockRoutesLength
  64. mockStartIndex = mockRoutes.mockStartIndex
  65. console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
  66. } catch (error) {
  67. console.log(chalk.redBright(error))
  68. }
  69. }
  70. })
  71. }