createProdMockServer.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* eslint-disable */
  2. import mockJs from 'mockjs';
  3. import { pathToRegexp } from 'path-to-regexp';
  4. const Mock = mockJs;
  5. export function createProdMockServer(mockList) {
  6. Mock.XHR.prototype.__send = Mock.XHR.prototype.send;
  7. Mock.XHR.prototype.send = function () {
  8. if (this.custom.xhr) {
  9. this.custom.xhr.withCredentials = this.withCredentials || false;
  10. if (this.responseType) {
  11. this.custom.xhr.responseType = this.responseType;
  12. }
  13. }
  14. if (this.custom.requestHeaders) {
  15. const headers = {};
  16. for (let k in this.custom.requestHeaders) {
  17. headers[k.toString().toLowerCase()] = this.custom.requestHeaders[k];
  18. }
  19. this.custom.options = Object.assign({}, this.custom.options, { headers });
  20. }
  21. this.__send.apply(this, arguments);
  22. };
  23. Mock.XHR.prototype.proxy_open = Mock.XHR.prototype.open;
  24. Mock.XHR.prototype.open = function () {
  25. let responseType = this.responseType;
  26. this.proxy_open(...arguments);
  27. if (this.custom.xhr) {
  28. if (responseType) {
  29. this.custom.xhr.responseType = responseType;
  30. }
  31. }
  32. };
  33. for (const { url, method, response, timeout } of mockList) {
  34. __setupMock__(timeout);
  35. Mock.mock(pathToRegexp(url, undefined, { end: false }), method || 'get', __XHR2ExpressReqWrapper__(response));
  36. }
  37. }
  38. function __param2Obj__(url) {
  39. const search = url.split('?')[1];
  40. if (!search) {
  41. return {};
  42. }
  43. return JSON.parse('{"' +
  44. decodeURIComponent(search)
  45. .replace(/"/g, '\\"')
  46. .replace(/&/g, '","')
  47. .replace(/=/g, '":"')
  48. .replace(/\+/g, ' ') +
  49. '"}');
  50. }
  51. function __XHR2ExpressReqWrapper__(handle) {
  52. return function (options) {
  53. let result = null;
  54. if (typeof handle === 'function') {
  55. const { body, type, url, headers } = options;
  56. let b = body;
  57. try {
  58. b = JSON.parse(body);
  59. }
  60. catch { }
  61. result = handle({
  62. method: type,
  63. body: b,
  64. query: __param2Obj__(url),
  65. headers,
  66. });
  67. }
  68. else {
  69. result = handle;
  70. }
  71. return Mock.mock(result);
  72. };
  73. }
  74. function __setupMock__(timeout = 0) {
  75. timeout &&
  76. Mock.setup({
  77. timeout,
  78. });
  79. }