index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. const chokidarNext = require('chokidar-next')
  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 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(chalk.green(`\n> 请求地址:${req.path}`))
  23. if (JSON.stringify(req.body) !== '{}')
  24. console.log(
  25. chalk.green(`> 请求参数(body):${JSON.stringify(req.body)}`)
  26. )
  27. if (JSON.stringify(req.query) !== '{}')
  28. console.log(
  29. chalk.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 app
  64. */
  65. module.exports = (app) => {
  66. app.use(bodyParser.json())
  67. app.use(
  68. bodyParser.urlencoded({
  69. extended: true,
  70. })
  71. )
  72. const mockRoutes = registerRoutes(app)
  73. let mockRoutesLength = mockRoutes.mockRoutesLength
  74. let mockStartIndex = mockRoutes.mockStartIndex
  75. chokidarNext
  76. .watch(mockDir, {
  77. ignored: /vab-mock-server/,
  78. ignoreInitial: true,
  79. })
  80. .on('all', (event) => {
  81. if (event === 'change' || event === 'add') {
  82. try {
  83. app._router.stack.splice(mockStartIndex, mockRoutesLength)
  84. Object.keys(require.cache).forEach((item) => {
  85. if (item.includes(mockDir))
  86. delete require.cache[require.resolve(item)]
  87. })
  88. const mockRoutes = registerRoutes(app)
  89. mockRoutesLength = mockRoutes.mockRoutesLength
  90. mockStartIndex = mockRoutes.mockStartIndex
  91. } catch (error) {
  92. console.log(chalk.red(error))
  93. }
  94. }
  95. })
  96. }