index.js 1.5 KB

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