Blame view

HHECS.Web/mock/mock-server.js 2.4 KB
胡菁 authored
1
2
3
4
5
const chokidar = require("chokidar");
const bodyParser = require("body-parser");
const chalk = require("chalk");
const path = require("path");
const Mock = require("mockjs");
胡菁 authored
6
胡菁 authored
7
const mockDir = path.join(process.cwd(), "mock");
胡菁 authored
8
9

function registerRoutes(app) {
胡菁 authored
10
11
12
13
14
  let mockLastIndex;
  const { mocks } = require("./index.js");
  const mocksForServer = mocks.map((route) => {
    return responseFake(route.url, route.type, route.response);
  });
胡菁 authored
15
  for (const mock of mocksForServer) {
胡菁 authored
16
17
    app[mock.type](mock.url, mock.response);
    mockLastIndex = app._router.stack.length;
胡菁 authored
18
  }
胡菁 authored
19
  const mockRoutesLength = Object.keys(mocksForServer).length;
胡菁 authored
20
21
  return {
    mockRoutesLength: mockRoutesLength,
胡菁 authored
22
23
    mockStartIndex: mockLastIndex - mockRoutesLength,
  };
胡菁 authored
24
25
26
}

function unregisterRoutes() {
胡菁 authored
27
  Object.keys(require.cache).forEach((i) => {
胡菁 authored
28
    if (i.includes(mockDir)) {
胡菁 authored
29
      delete require.cache[require.resolve(i)];
胡菁 authored
30
    }
胡菁 authored
31
  });
胡菁 authored
32
33
34
35
36
37
}

// for mock server
const responseFake = (url, type, respond) => {
  return {
    url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
胡菁 authored
38
    type: type || "get",
胡菁 authored
39
    response(req, res) {
胡菁 authored
40
41
42
43
44
45
46
      console.log("request invoke:" + req.path);
      res.json(
        Mock.mock(respond instanceof Function ? respond(req, res) : respond)
      );
    },
  };
};
胡菁 authored
47
胡菁 authored
48
module.exports = (app) => {
胡菁 authored
49
50
  // parse app.body
  // https://expressjs.com/en/4x/api.html#req.body
胡菁 authored
51
52
53
54
55
56
  app.use(bodyParser.json());
  app.use(
    bodyParser.urlencoded({
      extended: true,
    })
  );
胡菁 authored
57
胡菁 authored
58
59
60
  const mockRoutes = registerRoutes(app);
  var mockRoutesLength = mockRoutes.mockRoutesLength;
  var mockStartIndex = mockRoutes.mockStartIndex;
胡菁 authored
61
62

  // watch files, hot reload mock server
胡菁 authored
63
64
65
66
67
68
69
70
71
72
  chokidar
    .watch(mockDir, {
      ignored: /mock-server/,
      ignoreInitial: true,
    })
    .on("all", (event, path) => {
      if (event === "change" || event === "add") {
        try {
          // remove mock routes stack
          app._router.stack.splice(mockStartIndex, mockRoutesLength);
胡菁 authored
73
胡菁 authored
74
75
          // clear routes cache
          unregisterRoutes();
胡菁 authored
76
胡菁 authored
77
78
79
          const mockRoutes = registerRoutes(app);
          mockRoutesLength = mockRoutes.mockRoutesLength;
          mockStartIndex = mockRoutes.mockStartIndex;
胡菁 authored
80
胡菁 authored
81
82
83
84
85
86
87
88
          console.log(
            chalk.magentaBright(
              `\n > Mock Server hot reload success! changed  ${path}`
            )
          );
        } catch (error) {
          console.log(chalk.redBright(error));
        }
胡菁 authored
89
      }
胡菁 authored
90
91
    });
};