axios-wrapper.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. /* eslint-disable no-console */
  2. /* eslint-disable no-param-reassign */
  3. import { get, isObject } from 'lodash-es'
  4. import Axios from 'axios'
  5. import { trimData, isNullOrUndefined } from './util-methods'
  6. import { ErrorCode } from './error-code'
  7. let currentRequests = 0
  8. export class AxiosWrapper {
  9. constructor({ baseUrl = import.meta.env.VITE_APP_BASE_API, unwrap = true } = {}) {
  10. this.baseUrl = baseUrl
  11. this.unwrap = unwrap
  12. }
  13. baseUrl
  14. unwrap
  15. // 替换uri中的参数变量
  16. static merge(uri, query) {
  17. if (!uri.includes(':')) {
  18. return uri
  19. }
  20. const keys = []
  21. const regexp = /\/:([a-z0-9_]+)/gi
  22. let res
  23. // eslint-disable-next-line no-cond-assign
  24. while ((res = regexp.exec(uri)) != null) {
  25. keys.push(res[1])
  26. }
  27. keys.forEach((key) => {
  28. const val = get(query, key)
  29. if (!isNullOrUndefined(val)) {
  30. uri = uri.replace(`:${key}`, `${val}`)
  31. }
  32. })
  33. return uri
  34. }
  35. $get(uri, query, options) {
  36. return this.$request(uri, undefined, query, options)
  37. }
  38. $post(uri, data = {}, query, options) {
  39. return this.$request(uri, data, query, options)
  40. }
  41. $delete(uri, data = {}, query, options = {}) {
  42. options = { ...options, method: 'delete' }
  43. return this.$request(uri, data, query, options)
  44. }
  45. async $request(uri, data, query, options) {
  46. if (query && isObject(query)) {
  47. const keys = Object.keys(query)
  48. for (const key of keys) {
  49. const val = get(query, key)
  50. if (val === '') {
  51. delete query[key]
  52. }
  53. }
  54. }
  55. if (isObject(query) && isObject(options)) {
  56. options = { ...options, params: query, method: 'get' }
  57. } else if (isObject(query) && !query.params) {
  58. options = { params: query }
  59. } else if (isObject(query) && query.params) {
  60. options = query
  61. }
  62. if (!options) options = {}
  63. if (options.params) options.params = trimData(options.params, null, null)
  64. const params = get(options, 'params')
  65. const url = AxiosWrapper.merge(uri, params)
  66. currentRequests += 1
  67. // Indicator.open({
  68. // spinnerType: 'fading-circle',
  69. // });
  70. try {
  71. let returnData
  72. const axios = Axios.create({
  73. baseURL: this.baseUrl,
  74. withCredentials: true
  75. })
  76. // if (util.token && util.token !== null) axios.defaults.headers.common.Authorization = util.token;
  77. const token = localStorage.getItem('token')
  78. const apiToken = localStorage.getItem('apiToken')
  79. if (token) axios.defaults.headers.common['token'] = token
  80. if (apiToken) axios.defaults.headers.common['api-token'] = apiToken
  81. const res = await axios.request({
  82. method: isNullOrUndefined(data) ? 'get' : 'post',
  83. url,
  84. data,
  85. responseType: 'json',
  86. ...options
  87. })
  88. const returnRes = res.data
  89. const { errcode, errmsg, details } = returnRes
  90. if (errcode) {
  91. console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`)
  92. return returnRes
  93. }
  94. // unwrap data
  95. if (this.unwrap) {
  96. returnData = returnRes
  97. }
  98. // 处理apiToken
  99. const { apiToken: at, ...others } = returnData
  100. if (at) localStorage.setItem('apiToken', at)
  101. return others
  102. } catch (err) {
  103. let errmsg = '接口请求失败,请稍后重试'
  104. if (err.response) {
  105. const { status } = err.response
  106. if (status === 401) errmsg = '用户认证失败,请重新登录'
  107. if (status === 403) errmsg = '当前用户不允许执行该操作'
  108. }
  109. console.error(
  110. `[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} -
  111. ${err.message}`
  112. )
  113. return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message }
  114. } finally {
  115. /* eslint-disable */
  116. currentRequests -= 1
  117. if (currentRequests <= 0) {
  118. currentRequests = 0
  119. // Indicator.close();
  120. }
  121. }
  122. }
  123. }