index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import Mock from 'mockjs';
  2. import { param2Obj } from '../src/utils';
  3. import user from './user';
  4. import role from './role';
  5. import article from './article';
  6. import search from './remote-search';
  7. const mocks = [...user, ...role, ...article, ...search];
  8. // for front mock
  9. // please use it cautiously, it will redefine XMLHttpRequest,
  10. // which will cause many of your third-party libraries to be invalidated(like progress event).
  11. export function mockXHR() {
  12. // mock patch
  13. // https://github.com/nuysoft/Mock/issues/300
  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. // https://expressjs.com/en/4x/api.html#req
  30. result = respond({
  31. method: type,
  32. body: JSON.parse(body),
  33. query: param2Obj(url),
  34. });
  35. } else {
  36. result = respond;
  37. }
  38. return Mock.mock(result);
  39. };
  40. }
  41. for (const i of mocks) {
  42. Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response));
  43. }
  44. }
  45. export default mocks;