index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const Mock = require('mockjs')
  2. const { param2Obj } = require('./utils')
  3. const user = require('./user')
  4. const role = require('./role')
  5. const article = require('./article')
  6. const search = require('./remote-search')
  7. const device = require('./device')
  8. const mocks = [
  9. ...user,
  10. ...role,
  11. ...article,
  12. ...search,
  13. ...device
  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 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. module.exports = {
  53. mocks,
  54. mockXHR
  55. }