index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
  5. // +----------------------------------------------------------------------
  6. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  7. // +----------------------------------------------------------------------
  8. // | Author: CRMEB Team <admin@crmeb.com>
  9. // +----------------------------------------------------------------------
  10. import Mock from 'mockjs'
  11. import { param2Obj } from '../src/utils'
  12. import user from './user'
  13. import role from './role'
  14. import article from './article'
  15. import search from './remote-search'
  16. const mocks = [
  17. ...user,
  18. ...role,
  19. ...article,
  20. ...search
  21. ]
  22. // for front mock
  23. // please use it cautiously, it will redefine XMLHttpRequest,
  24. // which will cause many of your third-party libraries to be invalidated(like progress event).
  25. export function mockXHR() {
  26. // mock patch
  27. // https://github.com/nuysoft/Mock/issues/300
  28. Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  29. Mock.XHR.prototype.send = function() {
  30. if (this.custom.xhr) {
  31. this.custom.xhr.withCredentials = this.withCredentials || false
  32. if (this.responseType) {
  33. this.custom.xhr.responseType = this.responseType
  34. }
  35. }
  36. this.proxy_send(...arguments)
  37. }
  38. function XHR2ExpressReqWrap(respond) {
  39. return function(options) {
  40. let result = null
  41. if (respond instanceof Function) {
  42. const { body, type, url } = options
  43. // https://expressjs.com/en/4x/api.html#req
  44. result = respond({
  45. method: type,
  46. body: JSON.parse(body),
  47. query: param2Obj(url)
  48. })
  49. } else {
  50. result = respond
  51. }
  52. return Mock.mock(result)
  53. }
  54. }
  55. for (const i of mocks) {
  56. Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  57. }
  58. }
  59. export default mocks