index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 doc = require('./doc')
  8. const mocks = [
  9. // ...user,
  10. // ...role,
  11. // ...supplier,
  12. // ...auth
  13. ...doc
  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. function mockXHR() {
  19. Mock.setup({
  20. timeout: 800
  21. })
  22. // mock patch
  23. // https://github.com/nuysoft/Mock/issues/300
  24. Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  25. Mock.XHR.prototype.send = function() {
  26. if (this.custom.xhr) {
  27. this.custom.xhr.withCredentials = this.withCredentials || false
  28. if (this.responseType) {
  29. this.custom.xhr.responseType = this.responseType
  30. }
  31. }
  32. this.proxy_send(...arguments)
  33. }
  34. function XHR2ExpressReqWrap(respond) {
  35. return function(options) {
  36. let result = null
  37. if (respond instanceof Function) {
  38. const { body, type, url } = options
  39. // https://expressjs.com/en/4x/api.html#req
  40. result = respond({
  41. method: type,
  42. body: JSON.parse(body),
  43. query: param2Obj(url)
  44. })
  45. } else {
  46. result = respond
  47. }
  48. return Mock.mock(result)
  49. }
  50. }
  51. for (const i of mocks) {
  52. Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  53. }
  54. }
  55. module.exports = {
  56. mocks,
  57. mockXHR
  58. }