index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 { baseURL } = require('../src/config')
  7. const mockDir = path.join(process.cwd(), 'mock')
  8. const { handleMockArray } = require('./utils')
  9. /**
  10. *
  11. * @param app
  12. * @returns {{mockStartIndex: number, mockRoutesLength: number}}
  13. */
  14. const registerRoutes = (app) => {
  15. let mockLastIndex
  16. const mocks = []
  17. const mockArray = handleMockArray()
  18. mockArray.forEach((item) => {
  19. const obj = require(item)
  20. mocks.push(...obj)
  21. })
  22. const mocksForServer = mocks.map((route) => {
  23. return responseFake(route.url, route.type, route.response)
  24. })
  25. for (const mock of mocksForServer) {
  26. app[mock.type](mock.url, mock.response)
  27. mockLastIndex = app._router.stack.length
  28. }
  29. const mockRoutesLength = Object.keys(mocksForServer).length
  30. return {
  31. mockRoutesLength: mockRoutesLength,
  32. mockStartIndex: mockLastIndex - mockRoutesLength,
  33. }
  34. }
  35. /**
  36. *
  37. * @param url
  38. * @param type
  39. * @param respond
  40. * @returns {{response(*=, *=): void, type: (*|string), url: RegExp}}
  41. */
  42. const responseFake = (url, type, respond) => {
  43. return {
  44. url: new RegExp(`${baseURL}${url}`),
  45. type: type || 'get',
  46. response(req, res) {
  47. res.status(200)
  48. res.json(mock(respond instanceof Function ? respond(req, res) : respond))
  49. },
  50. }
  51. }
  52. /**
  53. *
  54. * @param app
  55. */
  56. module.exports = (app) => {
  57. app.use(bodyParser.json())
  58. app.use(
  59. bodyParser.urlencoded({
  60. extended: true,
  61. })
  62. )
  63. const mockRoutes = registerRoutes(app)
  64. let mockRoutesLength = mockRoutes.mockRoutesLength
  65. let mockStartIndex = mockRoutes.mockStartIndex
  66. chokidar
  67. .watch(mockDir, {
  68. ignored: /mock-server/,
  69. ignoreInitial: true,
  70. })
  71. .on('all', (event) => {
  72. if (event === 'change' || event === 'add') {
  73. try {
  74. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  75. Object.keys(require.cache).forEach((item) => {
  76. if (item.includes(mockDir)) {
  77. delete require.cache[require.resolve(item)]
  78. }
  79. })
  80. const mockRoutes = registerRoutes(app)
  81. mockRoutesLength = mockRoutes.mockRoutesLength
  82. mockStartIndex = mockRoutes.mockStartIndex
  83. } catch (error) {
  84. console.log(chalk.red(error))
  85. }
  86. }
  87. })
  88. }