index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import Mock from 'mockjs'
  2. import { param2Obj } from '../src/utils'
  3. import user from './user'
  4. import tag from './tag'
  5. import role from './role'
  6. import article from './article'
  7. import search from './remote-search'
  8. const mocks = [
  9. ...tag,
  10. ...user,
  11. ...role,
  12. ...article,
  13. ...search
  14. ]
  15. // for front mock
  16. // please use it cautiously, it will redefine XMLHttpRequest,
  17. // which will cause many of your third-party libraries to be invalidated(like progress event).
  18. export function mockXHR() {
  19. // mock patch
  20. // https://github.com/nuysoft/Mock/issues/300
  21. Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  22. Mock.XHR.prototype.send = function() {
  23. if (this.custom.xhr) {
  24. this.custom.xhr.withCredentials = this.withCredentials || false
  25. if (this.responseType) {
  26. this.custom.xhr.responseType = this.responseType
  27. }
  28. }
  29. this.proxy_send(...arguments)
  30. }
  31. function XHR2ExpressReqWrap(respond) {
  32. return function(options) {
  33. let result = null
  34. if (respond instanceof Function) {
  35. const { body, type, url } = options
  36. // https://expressjs.com/en/4x/api.html#req
  37. result = respond({
  38. method: type,
  39. body: JSON.parse(body),
  40. query: param2Obj(url)
  41. })
  42. } else {
  43. result = respond
  44. }
  45. return Mock.mock(result)
  46. }
  47. }
  48. for (const i of mocks) {
  49. Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  50. }
  51. }
  52. export default mocks