index.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. const chokidarNext = require('chokidar')
  2. const bodyParser = require('body-parser')
  3. const chalkNext = 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 url
  12. * @param type
  13. * @param respond
  14. * @returns {{response(*=, *=): void, type: (*|string), url: RegExp}}
  15. */
  16. const responseFake = (url, type, respond) => {
  17. return {
  18. url: new RegExp(`${baseURL}${url}`),
  19. type: type || 'get',
  20. response(req, res) {
  21. res.status(200)
  22. console.log(chalkNext.green(`\n> 请求地址:${req.path}`))
  23. if (JSON.stringify(req.body) !== '{}')
  24. console.log(
  25. chalkNext.green(`> 请求参数(body):${JSON.stringify(req.body)}`)
  26. )
  27. if (JSON.stringify(req.query) !== '{}')
  28. console.log(
  29. chalkNext.green(`> 请求参数(query):${JSON.stringify(req.query)}`)
  30. )
  31. res.json(mock(respond instanceof Function ? respond(req, res) : respond))
  32. },
  33. }
  34. }
  35. /**
  36. *
  37. * @param app
  38. * @returns {{mockStartIndex: number, mockRoutesLength: number}}
  39. */
  40. const registerRoutes = (app) => {
  41. let mockLastIndex
  42. const mocks = []
  43. const mockArray = handleMockArray()
  44. mockArray.forEach((item) => {
  45. const obj = require(item)
  46. mocks.push(...obj)
  47. })
  48. const mocksForServer = mocks.map((route) =>
  49. responseFake(route.url, route.type, route.response)
  50. )
  51. const mockRoutesLength = Object.keys(mocksForServer).length
  52. for (const item of mocksForServer) {
  53. app[item.type](item.url, item.response)
  54. mockLastIndex = app._router.stack.length
  55. }
  56. return {
  57. mockRoutesLength,
  58. mockStartIndex: mockLastIndex - mockRoutesLength,
  59. }
  60. }
  61. /**
  62. *
  63. * @param middlewares
  64. * @param devServer
  65. */
  66. module.exports = (middlewares, devServer) => {
  67. if (!devServer) {
  68. throw new Error('webpack-dev-server is not defined')
  69. }
  70. const app = devServer.app
  71. app.use(bodyParser.json())
  72. app.use(
  73. bodyParser.urlencoded({
  74. extended: true,
  75. })
  76. )
  77. const mockRoutes = registerRoutes(app)
  78. let mockRoutesLength = mockRoutes.mockRoutesLength
  79. let mockStartIndex = mockRoutes.mockStartIndex
  80. chokidarNext
  81. .watch(mockDir, {
  82. ignored: /vab-mock-server/,
  83. ignoreInitial: true,
  84. })
  85. .on('all', (event) => {
  86. if (event === 'change' || event === 'add') {
  87. try {
  88. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  89. Object.keys(require.cache).forEach((item) => {
  90. if (item.includes(mockDir))
  91. delete require.cache[require.resolve(item)]
  92. })
  93. const mockRoutes = registerRoutes(app)
  94. mockRoutesLength = mockRoutes.mockRoutesLength
  95. mockStartIndex = mockRoutes.mockStartIndex
  96. } catch (error) {
  97. console.log(chalkNext.red(error))
  98. }
  99. }
  100. })
  101. return middlewares
  102. }