2
0

index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import Mock from 'mockjs'
  2. import { param2Obj } from '../src/utils'
  3. import user from './user'
  4. import table from './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. export 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. // for mock server
  47. const responseFake = (url, type, respond) => {
  48. return {
  49. url: new RegExp(`/mock${url}`),
  50. type: type || 'get',
  51. response(req, res) {
  52. res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
  53. }
  54. }
  55. }
  56. export default mocks.map(route => {
  57. return responseFake(route.url, route.type, route.response)
  58. })