index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const Mock = require('mockjs')
  2. const { param2Obj } = require('./utils')
  3. const common = require('./common')
  4. const user = require('./user')
  5. const role = require('./role')
  6. const article = require('./article')
  7. const search = require('./remote-search')
  8. const mocks = [
  9. ...common,
  10. ...user,
  11. ...role,
  12. ...article,
  13. ...search
  14. ]
  15. console.log('# 注意使用了 mock .')
  16. // for front mock
  17. // please use it cautiously, it will redefine XMLHttpRequest,
  18. // which will cause many of your third-party libraries to be invalidated(like progress event).
  19. function mockXHR() {
  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. }