static.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * @copyright chuzhixin 1204505056@qq.com
  3. * @description 导入所有 controller 模块,浏览器环境中自动输出controller文件夹下Mock接口,请勿修改。
  4. */
  5. import Mock from "mockjs";
  6. import { paramObj } from "../src/utils";
  7. const mocks = [];
  8. const files = require.context("./controller", false, /\.js$/);
  9. files.keys().forEach((key) => {
  10. const obj = files(key).default;
  11. mocks.push(...obj);
  12. });
  13. export function mockXHR() {
  14. Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send;
  15. Mock.XHR.prototype.send = function () {
  16. if (this.custom.xhr) {
  17. this.custom.xhr.withCredentials = this.withCredentials || false;
  18. if (this.responseType) {
  19. this.custom.xhr.responseType = this.responseType;
  20. }
  21. }
  22. this.proxy_send(...arguments);
  23. };
  24. function XHR2ExpressReqWrap(respond) {
  25. return function (options) {
  26. let result = null;
  27. if (respond instanceof Function) {
  28. const { body, type, url } = options;
  29. result = respond({
  30. method: type,
  31. body: JSON.parse(body),
  32. query: paramObj(url),
  33. });
  34. } else {
  35. result = respond;
  36. }
  37. return Mock.mock(result);
  38. };
  39. }
  40. for (const i of mocks) {
  41. Mock.mock(
  42. new RegExp(i.url),
  43. i.type || "get",
  44. XHR2ExpressReqWrap(i.response)
  45. );
  46. }
  47. }