index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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(`${process.env.VUE_APP_BASE_API}${url}`),
  50. type: type || 'get',
  51. response(req, res) {
  52. console.log('request invoke:' + req.path)
  53. res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
  54. }
  55. }
  56. }
  57. export default mocks.map(route => {
  58. return responseFake(route.url, route.type, route.response)
  59. })