mock-server.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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.server, 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, server, type, respond) => {
  32. console.log(server)
  33. var url = new RegExp(`${process.env.VUE_APP_BASE_API}${url}`);
  34. if(server == 'worker') {
  35. url = new RegExp(`${process.env.VUE_APP_WORKER_API}${url}`);
  36. }
  37. return {
  38. url: url,
  39. type: type || 'get',
  40. response(req, res) {
  41. console.log('request invoke:' + req.path)
  42. res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
  43. }
  44. }
  45. }
  46. module.exports = app => {
  47. // parse app.body
  48. // https://expressjs.com/en/4x/api.html#req.body
  49. app.use(bodyParser.json())
  50. app.use(bodyParser.urlencoded({
  51. extended: true
  52. }))
  53. const mockRoutes = registerRoutes(app)
  54. var mockRoutesLength = mockRoutes.mockRoutesLength
  55. var mockStartIndex = mockRoutes.mockStartIndex
  56. // watch files, hot reload mock server
  57. chokidar.watch(mockDir, {
  58. ignored: /mock-server/,
  59. ignoreInitial: true
  60. }).on('all', (event, path) => {
  61. if (event === 'change' || event === 'add') {
  62. try {
  63. // remove mock routes stack
  64. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  65. // clear routes cache
  66. unregisterRoutes()
  67. const mockRoutes = registerRoutes(app)
  68. mockRoutesLength = mockRoutes.mockRoutesLength
  69. mockStartIndex = mockRoutes.mockStartIndex
  70. console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
  71. } catch (error) {
  72. console.log(chalk.redBright(error))
  73. }
  74. }
  75. })
  76. }