mockServer.js 2.5 KB

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