index.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. /* eslint-disable */
  21. this.proxy_send(...arguments)
  22. }
  23. function XHR2ExpressReqWrap(respond: any) {
  24. return function(options: any) {
  25. let result = null
  26. if (respond instanceof Function) {
  27. const { body, type, url } = options
  28. // https://expressjs.com/en/4x/api.html#req
  29. result = respond({
  30. method: type,
  31. body: JSON.parse(body),
  32. query: param2Obj(url)
  33. })
  34. } else {
  35. result = respond
  36. }
  37. return Mock.mock(result)
  38. }
  39. }
  40. for (const i of mocks) {
  41. Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  42. }
  43. }
  44. // for mock server
  45. const responseFake = (url: string, type: string, respond: any) => {
  46. return {
  47. url: new RegExp(`${url}`),
  48. type: type || 'get',
  49. response(req: any, res: any) {
  50. res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
  51. }
  52. }
  53. }
  54. export default mocks.map(route => {
  55. return responseFake(route.url, route.type, route.response)
  56. })