index.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. if (JSON.stringify(req.body) !== '{}') {
  49. console.log(chalk.green(`> 请求地址:${req.path}`))
  50. console.log(chalk.green(`> 请求参数:${JSON.stringify(req.body)}\n`))
  51. } else {
  52. console.log(chalk.green(`> 请求地址:${req.path}\n`))
  53. }
  54. res.json(mock(respond instanceof Function ? respond(req, res) : respond))
  55. },
  56. }
  57. }
  58. /**
  59. *
  60. * @param app
  61. */
  62. module.exports = (app) => {
  63. app.use(bodyParser.json())
  64. app.use(
  65. bodyParser.urlencoded({
  66. extended: true,
  67. })
  68. )
  69. const mockRoutes = registerRoutes(app)
  70. let mockRoutesLength = mockRoutes.mockRoutesLength
  71. let mockStartIndex = mockRoutes.mockStartIndex
  72. chokidar
  73. .watch(mockDir, {
  74. ignored: /mock-server/,
  75. ignoreInitial: true,
  76. })
  77. .on('all', (event) => {
  78. if (event === 'change' || event === 'add') {
  79. try {
  80. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  81. Object.keys(require.cache).forEach((item) => {
  82. if (item.includes(mockDir)) {
  83. delete require.cache[require.resolve(item)]
  84. }
  85. })
  86. const mockRoutes = registerRoutes(app)
  87. mockRoutesLength = mockRoutes.mockRoutesLength
  88. mockStartIndex = mockRoutes.mockStartIndex
  89. } catch (error) {
  90. console.log(chalk.red(error))
  91. }
  92. }
  93. })
  94. }