| 1 | const createApi = fetchFunc => options => (...args) => { |
| 2 | let finalOpts |
| 3 | const argsName = ['options', 'successCallBack', 'errorCallBack', 'dispatch'] |
| 4 | // options 可以是 url,或完整的 options 对象 |
| 5 | if (typeof options === 'string') { |
| 6 | finalOpts = { url: options } |
| 7 | } else { |
| 8 | finalOpts = { ...options } |
| 9 | } |
| 10 | |
| 11 | const temArgs = {} |
| 12 | if (args) { |
| 13 | // args 第一个参数,options 可以忽略 |
| 14 | let i = 0 |
| 15 | if (args[0] !== null && typeof args[0] === 'object') { |
| 16 | i = 1 |
| 17 | finalOpts = Object.assign(finalOpts, args[0]) |
| 18 | } |
| 19 | |
| 20 | // eslint-disable-next-line no-plusplus |
| 21 | for (let j = i; j < args.length; j++) { |
| 22 | // eslint-disable-next-line no-mixed-operators |
| 23 | temArgs[argsName[j - i + 1]] = args[j] |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | if (temArgs.successCallBack) { |
| 28 | finalOpts.onSuccess = temArgs.successCallBack |
| 29 | } |
| 30 | |
| 31 | if (temArgs.errorCallBack) { |
| 32 | finalOpts.onError = temArgs.errorCallBack |
| 33 | } |
| 34 | fetchFunc(finalOpts, temArgs.dispatch) |
| 35 | } |
| 36 | |
| 37 | export default createApi |