mock-server.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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(
  46. bodyParser.urlencoded({
  47. extended: true
  48. })
  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
  55. .watch(mockDir, {
  56. ignored: /mock-server/,
  57. ignoreInitial: true
  58. })
  59. .on('all', (event, path) => {
  60. if (event === 'change' || event === 'add') {
  61. try {
  62. // remove mock routes stack
  63. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  64. // clear routes cache
  65. unregisterRoutes()
  66. const mockRoutes = registerRoutes(app)
  67. mockRoutesLength = mockRoutes.mockRoutesLength
  68. mockStartIndex = mockRoutes.mockStartIndex
  69. console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
  70. } catch (error) {
  71. console.log(chalk.redBright(error))
  72. }
  73. }
  74. })
  75. }