request.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { getArgs, getRequestConfig, getRequestData, getRequestPath, isSuccess, notifyErrorMessage } from './util'
  2. import axiosConfig from '_config/axios-config'
  3. import CipMessage from '@cip/components/cip-message'
  4. import CancelLoading from '@cip/components/cip-cancel-loading/Loading'
  5. import { RequestQueue } from './request-queue'
  6. const { appendTimestamp, DEFAULT_SUCCESS_CODE } = axiosConfig
  7. const requestQueue = new RequestQueue()
  8. /**
  9. * @return {Promise<*>}
  10. */
  11. // type, apiName, path, params = {}, options = {}
  12. export const request = async (...args) => {
  13. // 此处需要兼容以前的data和params
  14. let { method = 'get', apiName, url, data, params = {}, pathParams = {}, options = {} } = getArgs(args)
  15. method = method.toLocaleLowerCase()
  16. if (!['get', 'delete', 'post', 'put'].includes(method)) {
  17. const message = `未经过允许的请求类型${method}`
  18. CipMessage({ type: 'error', message })
  19. throw new Error(message)
  20. }
  21. let config = {}
  22. // 合并data、params、pathParams的参数 为了兼容老代码
  23. const requestUrl = getRequestPath(apiName, url, Object.assign({}, data, params, pathParams))
  24. // 针对application/x-www-form-urlencoded的data进行格式化
  25. if (['post', 'put'].includes(method)) {
  26. data = getRequestData(data, options)
  27. }
  28. config = getRequestConfig(params, options, appendTimestamp)
  29. let cancelLoading
  30. try {
  31. // 可取消的接口弹出框配置 {message: string, btnName: string, duration: number }
  32. if (options.enableCancel) {
  33. // 跳出弹出框, 弹出框点击取消调用config._cancel(),取消接口
  34. cancelLoading = CancelLoading({
  35. ...options.enableCancel,
  36. onCancel: () => {
  37. config._cancel()
  38. }
  39. })
  40. }
  41. const res = await requestQueue.request({
  42. method: method,
  43. url: requestUrl,
  44. data,
  45. config
  46. })
  47. if (isSuccess(res, options, DEFAULT_SUCCESS_CODE)) {
  48. return res.data
  49. } else {
  50. // 此异常数据将页面代码中使用
  51. throw res.data
  52. }
  53. } catch (e) {
  54. if (options.autoNotify !== false) {
  55. const message = await notifyErrorMessage(e)
  56. CipMessage({ type: 'error', message })
  57. }
  58. throw e
  59. } finally {
  60. if (options.enableCancel) {
  61. // 如果弹出框存在的话,隐藏弹出框;
  62. cancelLoading.hide()
  63. }
  64. }
  65. }