axios-wrapper.js 4.4 KB

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