index.ts 1.8 KB

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