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