index.ts 1.7 KB

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