index.js 1.5 KB

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