index.js 1.7 KB

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