index.js 1.8 KB

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