Blame view

HHECS.Web/mock/index.js 1.39 KB
胡菁 authored
1
2
const Mock = require("mockjs");
const { param2Obj } = require("./utils");
胡菁 authored
3
胡菁 authored
4
5
const user = require("./user");
const table = require("./table");
胡菁 authored
6
胡菁 authored
7
const mocks = [...user, ...table];
胡菁 authored
8
9
10
11
12
13
14

// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
function mockXHR() {
  // mock patch
  // https://github.com/nuysoft/Mock/issues/300
胡菁 authored
15
16
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send;
  Mock.XHR.prototype.send = function () {
胡菁 authored
17
    if (this.custom.xhr) {
胡菁 authored
18
      this.custom.xhr.withCredentials = this.withCredentials || false;
胡菁 authored
19
20

      if (this.responseType) {
胡菁 authored
21
        this.custom.xhr.responseType = this.responseType;
胡菁 authored
22
23
      }
    }
胡菁 authored
24
25
    this.proxy_send(...arguments);
  };
胡菁 authored
26
27

  function XHR2ExpressReqWrap(respond) {
胡菁 authored
28
29
    return function (options) {
      let result = null;
胡菁 authored
30
      if (respond instanceof Function) {
胡菁 authored
31
        const { body, type, url } = options;
胡菁 authored
32
33
34
35
        // https://expressjs.com/en/4x/api.html#req
        result = respond({
          method: type,
          body: JSON.parse(body),
胡菁 authored
36
37
          query: param2Obj(url),
        });
胡菁 authored
38
      } else {
胡菁 authored
39
        result = respond;
胡菁 authored
40
      }
胡菁 authored
41
42
      return Mock.mock(result);
    };
胡菁 authored
43
44
45
  }

  for (const i of mocks) {
胡菁 authored
46
47
48
49
50
    Mock.mock(
      new RegExp(i.url),
      i.type || "get",
      XHR2ExpressReqWrap(i.response)
    );
胡菁 authored
51
52
53
54
55
  }
}

module.exports = {
  mocks,
胡菁 authored
56
57
  mockXHR,
};