index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // 请谨慎使用,它会重写浏览器的XMLHttpRequest, 这将导致许多第三方库失效(如进度事件)。
  10. export function mockXHR() {
  11. Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  12. Mock.XHR.prototype.send = function () {
  13. if (this.custom.xhr) {
  14. this.custom.xhr.withCredentials = this.withCredentials || false
  15. if (this.responseType) {
  16. this.custom.xhr.responseType = this.responseType
  17. }
  18. }
  19. this.proxy_send(...arguments)
  20. }
  21. function XHR2ExpressReqWrap(respond) {
  22. return function (options) {
  23. let result = null
  24. if (respond instanceof Function) {
  25. const { body, type, url } = options
  26. result = respond({
  27. method: type,
  28. body: JSON.parse(body),
  29. query: param2Obj(url)
  30. })
  31. } else {
  32. result = respond
  33. }
  34. return Mock.mock(result)
  35. }
  36. }
  37. for (const i of mocks) {
  38. Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  39. }
  40. }
  41. // mock server
  42. const responseFake = (url, type, respond) => {
  43. return {
  44. url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
  45. type: type || 'get',
  46. response(req, res) {
  47. console.log('request invoke:' + req.path)
  48. res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
  49. }
  50. }
  51. }
  52. export default mocks.map(route => {
  53. return responseFake(route.url, route.type, route.response)
  54. })