2
0

index.js 1.4 KB

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