index.js 1.4 KB

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