index.js 1.3 KB

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