index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import Mock from 'mockjs'
  2. import { param2Obj } from '../src/utils'
  3. import role from './role'
  4. import article from './article'
  5. import search from './remote-search'
  6. const mocks = [
  7. ...role,
  8. ...article,
  9. ...search
  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. // mock patch
  16. // https://github.com/nuysoft/Mock/issues/300
  17. Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  18. Mock.XHR.prototype.send = function() {
  19. if (this.custom.xhr) {
  20. this.custom.xhr.withCredentials = this.withCredentials || false
  21. if (this.responseType) {
  22. this.custom.xhr.responseType = this.responseType
  23. }
  24. }
  25. this.proxy_send(...arguments)
  26. }
  27. function XHR2ExpressReqWrap(respond) {
  28. return function(options) {
  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, type, respond) => {
  50. return {
  51. url: new RegExp(`/mock${url}`),
  52. type: type || 'get',
  53. response(req, res) {
  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. })