2
0

mock-server.js 1.8 KB

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