index.js 1.5 KB

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