123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- import { getArgs, getRequestConfig, getRequestData, getRequestPath, isSuccess, notifyErrorMessage } from './util'
- import axiosConfig from '_config/axios-config'
- import CipMessage from '@cip/components/cip-message'
- import CancelLoading from '@cip/components/cip-cancel-loading/Loading'
- import { RequestQueue } from './request-queue'
- const { appendTimestamp, DEFAULT_SUCCESS_CODE } = axiosConfig
- const requestQueue = new RequestQueue()
- /**
- * @return {Promise<*>}
- */
- // type, apiName, path, params = {}, options = {}
- export const request = async (...args) => {
- // 此处需要兼容以前的data和params
- let { method = 'get', apiName, url, data, params = {}, pathParams = {}, options = {} } = getArgs(args)
- method = method.toLocaleLowerCase()
- if (!['get', 'delete', 'post', 'put'].includes(method)) {
- const message = `未经过允许的请求类型${method}`
- CipMessage({ type: 'error', message })
- throw new Error(message)
- }
- let config = {}
- // 合并data、params、pathParams的参数 为了兼容老代码
- const requestUrl = getRequestPath(apiName, url, Object.assign({}, data, params, pathParams))
- // 针对application/x-www-form-urlencoded的data进行格式化
- if (['post', 'put'].includes(method)) {
- data = getRequestData(data, options)
- }
- config = getRequestConfig(params, options, appendTimestamp)
- let cancelLoading
- try {
- // 可取消的接口弹出框配置 {message: string, btnName: string, duration: number }
- if (options.enableCancel) {
- // 跳出弹出框, 弹出框点击取消调用config._cancel(),取消接口
- cancelLoading = CancelLoading({
- ...options.enableCancel,
- onCancel: () => {
- config._cancel()
- }
- })
- }
- const res = await requestQueue.request({
- method: method,
- url: requestUrl,
- data,
- config
- })
- if (isSuccess(res, options, DEFAULT_SUCCESS_CODE)) {
- return res.data
- } else {
- // 此异常数据将页面代码中使用
- throw res.data
- }
- } catch (e) {
- if (options.autoNotify !== false) {
- const message = await notifyErrorMessage(e)
- CipMessage({ type: 'error', message })
- }
- throw e
- } finally {
- if (options.enableCancel) {
- // 如果弹出框存在的话,隐藏弹出框;
- cancelLoading.hide()
- }
- }
- }
|