mock-server.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // remove mock routes stack
  45. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  46. // clear routes cache
  47. unregisterRoutes()
  48. const mockRoutes = registerRoutes(app)
  49. mockRoutesLength = mockRoutes.mockRoutesLength
  50. mockStartIndex = mockRoutes.mockStartIndex
  51. console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
  52. }
  53. })
  54. }