index.js 1.1 KB

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