| sijun.li | 9646230 | 2020-07-24 10:08:05 +0800 | [diff] [blame^] | 1 | const Mock = require('mockjs') | 
|  | 2 | const { param2Obj } = require('./utils') | 
|  | 3 |  | 
|  | 4 | const user = require('./user') | 
|  | 5 | const role = require('./role') | 
|  | 6 | const article = require('./article') | 
|  | 7 | const search = require('./remote-search') | 
|  | 8 |  | 
|  | 9 | const 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). | 
|  | 19 | function 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 |  | 
|  | 57 | module.exports = { | 
|  | 58 | mocks, | 
|  | 59 | mockXHR | 
|  | 60 | } |