http-client.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /* eslint-disable */
  2. /* tslint:disable */
  3. /*
  4. * ---------------------------------------------------------------
  5. * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
  6. * ## ##
  7. * ## AUTHOR: acacode ##
  8. * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
  9. * ---------------------------------------------------------------
  10. */
  11. import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, HeadersDefaults, RawAxiosRequestHeaders, ResponseType } from 'axios'
  12. import { ElLoading, ElMessage, LoadingOptions } from 'element-plus'
  13. import { storeToRefs } from 'pinia'
  14. import { useUserInfo } from '/@/stores/userInfo'
  15. export type QueryParamsType = Record<string | number, any>
  16. export interface FullRequestParams extends Omit<AxiosRequestConfig, 'data' | 'params' | 'url' | 'responseType'> {
  17. /** set parameter to `true` for call `securityWorker` for this request */
  18. secure?: boolean
  19. /** request path */
  20. path: string
  21. /** content type of request body */
  22. type?: ContentType
  23. /** query params */
  24. query?: QueryParamsType
  25. /** format of response (i.e. response.json() -> format: "json") */
  26. format?: ResponseType
  27. /** request body */
  28. body?: unknown
  29. /** 显示错误消息 */
  30. showErrorMessage?: boolean
  31. /** 显示成功消息 */
  32. showSuccessMessage?: boolean
  33. /** 登录访问 */
  34. login?: boolean
  35. /** 加载中 */
  36. loading?: boolean
  37. /** 加载中选项 */
  38. loadingOptions?: LoadingOptions
  39. /** 取消重复请求 */
  40. cancelRepeatRequest?: boolean
  41. responseType?: 'blob' | 'json' | 'text'
  42. }
  43. export type RequestParams = Omit<FullRequestParams, 'body' | 'method' | 'query' | 'path'>
  44. export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, 'data' | 'cancelToken'> {
  45. securityWorker?: (securityData: SecurityDataType | null) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void
  46. secure?: boolean
  47. format?: ResponseType
  48. }
  49. export enum ContentType {
  50. Json = 'application/json',
  51. FormData = 'multipart/form-data',
  52. UrlEncoded = 'application/x-www-form-urlencoded',
  53. Text = 'text/plain',
  54. }
  55. export interface LoadingInstance {
  56. target: any
  57. count: number
  58. }
  59. const pendingMap = new Map()
  60. const loadingInstance: LoadingInstance = {
  61. target: null,
  62. count: 0,
  63. }
  64. export class HttpClient<SecurityDataType = unknown> {
  65. public instance: AxiosInstance
  66. private securityData: SecurityDataType | null = null
  67. private securityWorker?: ApiConfig<SecurityDataType>['securityWorker']
  68. private secure?: boolean
  69. private format?: ResponseType
  70. constructor({ securityWorker, secure, format, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
  71. this.instance = axios.create({ ...axiosConfig, timeout: 60000, baseURL: axiosConfig.baseURL || import.meta.env.VITE_API_URL })
  72. this.secure = secure
  73. this.format = format
  74. this.securityWorker = securityWorker
  75. }
  76. public setSecurityData = (data: SecurityDataType | null) => {
  77. this.securityData = data
  78. }
  79. protected mergeRequestParams(params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
  80. const method = params1.method || (params2 && params2.method)
  81. return {
  82. ...this.instance.defaults,
  83. ...params1,
  84. ...(params2 || {}),
  85. headers: {
  86. ...((method && this.instance.defaults.headers[method.toLowerCase() as keyof HeadersDefaults]) || {}),
  87. ...(params1.headers || {}),
  88. ...((params2 && params2.headers) || {}),
  89. } as RawAxiosRequestHeaders,
  90. }
  91. }
  92. protected stringifyFormItem(formItem: unknown) {
  93. if (typeof formItem === 'object' && formItem !== null) {
  94. return JSON.stringify(formItem)
  95. } else {
  96. return `${formItem}`
  97. }
  98. }
  99. protected createFormData(input: Record<string, unknown>): FormData {
  100. return Object.keys(input || {}).reduce((formData, key) => {
  101. const property = input[key]
  102. const propertyContent: any[] = property instanceof Array ? property : [property]
  103. for (const formItem of propertyContent) {
  104. const isFileType = formItem instanceof Blob || formItem instanceof File
  105. formData.append(key, isFileType ? formItem : this.stringifyFormItem(formItem))
  106. }
  107. return formData
  108. }, new FormData())
  109. }
  110. /**
  111. * 错误处理
  112. * @param {*} error
  113. */
  114. protected errorHandle(error: any) {
  115. if (!error) {
  116. return
  117. }
  118. if (axios.isCancel(error)) return console.error('请求重复已被自动取消:' + error.message)
  119. let message = ''
  120. if (error.response) {
  121. switch (error.response.status) {
  122. case 302:
  123. message = '接口重定向'
  124. break
  125. case 400:
  126. message = '参数不正确'
  127. break
  128. case 401:
  129. message = '您还没有登录'
  130. break
  131. case 403:
  132. message = '您没有权限操作'
  133. break
  134. case 404:
  135. message = '请求地址出错:' + error.response.config.url
  136. break
  137. case 408:
  138. message = '请求超时'
  139. break
  140. case 409:
  141. message = '系统已存在相同数据'
  142. break
  143. case 500:
  144. message = '服务器内部错误'
  145. break
  146. case 501:
  147. message = '服务未实现'
  148. break
  149. case 502:
  150. message = '网关错误'
  151. break
  152. case 503:
  153. message = '服务不可用'
  154. break
  155. case 504:
  156. message = '服务暂时无法访问,请稍后再试'
  157. break
  158. case 505:
  159. message = 'HTTP版本不受支持'
  160. break
  161. default:
  162. message = '异常问题,请联系网站管理员'
  163. break
  164. }
  165. }
  166. if (error.message.includes('timeout')) message = '请求超时'
  167. if (error.message.includes('Network')) message = window.navigator.onLine ? '服务端异常' : '您已断网'
  168. if (message) {
  169. ElMessage.error({ message, grouping: true })
  170. }
  171. }
  172. /**
  173. * 刷新token
  174. * @param {*} config
  175. */
  176. protected async refreshToken(config: any) {
  177. const storesUseUserInfo = useUserInfo()
  178. const { userInfos } = storeToRefs(storesUseUserInfo)
  179. const token = userInfos.value.token
  180. if (!token) {
  181. storesUseUserInfo.clear()
  182. return Promise.reject(config)
  183. }
  184. if (window.tokenRefreshing) {
  185. window.requests = window.requests ? window.requests : []
  186. return new Promise((resolve) => {
  187. window.requests.push(() => {
  188. resolve(this.instance(config))
  189. })
  190. })
  191. }
  192. window.tokenRefreshing = true
  193. return this.request<AxiosResponse, any>({
  194. path: `/api/admin/auth/refresh`,
  195. method: 'GET',
  196. secure: true,
  197. format: 'json',
  198. login: false,
  199. query: {
  200. token: token,
  201. },
  202. })
  203. .then((res) => {
  204. if (res?.success) {
  205. const token = res.data.token
  206. storesUseUserInfo.setToken(token)
  207. if (window.requests?.length > 0) {
  208. window.requests.forEach((apiRequest) => apiRequest())
  209. window.requests = []
  210. }
  211. return this.instance(config)
  212. } else {
  213. storesUseUserInfo.clear()
  214. return Promise.reject(res)
  215. }
  216. })
  217. .catch((error) => {
  218. storesUseUserInfo.clear()
  219. return Promise.reject(error)
  220. })
  221. .finally(() => {
  222. window.tokenRefreshing = false
  223. })
  224. }
  225. /**
  226. * 储存每个请求的唯一cancel回调, 以此为标识
  227. */
  228. protected addPending(config: AxiosRequestConfig) {
  229. const pendingKey = this.getPendingKey(config)
  230. config.cancelToken =
  231. config.cancelToken ||
  232. new axios.CancelToken((cancel) => {
  233. if (!pendingMap.has(pendingKey)) {
  234. pendingMap.set(pendingKey, cancel)
  235. }
  236. })
  237. }
  238. /**
  239. * 删除重复的请求
  240. */
  241. protected removePending(config: AxiosRequestConfig) {
  242. const pendingKey = this.getPendingKey(config)
  243. if (pendingMap.has(pendingKey)) {
  244. const cancelToken = pendingMap.get(pendingKey)
  245. cancelToken(pendingKey)
  246. pendingMap.delete(pendingKey)
  247. }
  248. }
  249. /**
  250. * 生成每个请求的唯一key
  251. */
  252. protected getPendingKey(config: AxiosRequestConfig) {
  253. let { data, headers } = config
  254. headers = headers as RawAxiosRequestHeaders
  255. const { url, method, params } = config
  256. if (typeof data === 'string') data = JSON.parse(data)
  257. return [url, method, headers && headers.Authorization ? headers.Authorization : '', JSON.stringify(params), JSON.stringify(data)].join('&')
  258. }
  259. /**
  260. * 关闭Loading层实例
  261. */
  262. protected closeLoading(loading: boolean = false) {
  263. if (loading && loadingInstance.count > 0) loadingInstance.count--
  264. if (loadingInstance.count === 0) {
  265. loadingInstance.target.close()
  266. loadingInstance.target = null
  267. }
  268. }
  269. public request = async <T = any, _E = any>({
  270. secure,
  271. path,
  272. type,
  273. query,
  274. format,
  275. body,
  276. showErrorMessage = true,
  277. showSuccessMessage = false,
  278. login = true,
  279. loading = false,
  280. loadingOptions = {},
  281. cancelRepeatRequest = false,
  282. ...params
  283. }: FullRequestParams & { responseType?: 'blob' | 'json' | 'text' }): Promise<T> => {
  284. const secureParams =
  285. ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {}
  286. const requestParams = this.mergeRequestParams(params, secureParams)
  287. const responseFormat = format || this.format || undefined
  288. if (type === ContentType.FormData && body && body !== null && typeof body === 'object') {
  289. body = this.createFormData(body as Record<string, unknown>)
  290. }
  291. if (type === ContentType.Text && body && body !== null && typeof body !== 'string') {
  292. body = JSON.stringify(body)
  293. }
  294. // 请求拦截
  295. this.instance.interceptors.request.use(
  296. (config) => {
  297. this.removePending(config)
  298. cancelRepeatRequest && this.addPending(config)
  299. if (loading) {
  300. loadingInstance.count++
  301. if (loadingInstance.count === 1) {
  302. loadingInstance.target = ElLoading.service(loadingOptions)
  303. }
  304. }
  305. const { userInfos } = storeToRefs(useUserInfo())
  306. const accessToken = userInfos.value.token
  307. config.headers!['Authorization'] = `Bearer ${accessToken}`
  308. return config
  309. },
  310. (error) => {
  311. return Promise.reject(error)
  312. }
  313. )
  314. // 响应拦截
  315. this.instance.interceptors.response.use(
  316. (res) => {
  317. this.removePending(res.config)
  318. loading && this.closeLoading(loading)
  319. const data = res.data
  320. if (data.success) {
  321. if (showSuccessMessage) {
  322. ElMessage.success({ message: data.msg ? data.msg : '操作成功', grouping: true })
  323. }
  324. } else {
  325. if (showErrorMessage) {
  326. ElMessage.error({ message: data.msg ? data.msg : '操作失败', grouping: true })
  327. }
  328. // return Promise.reject(res)
  329. }
  330. return res
  331. },
  332. async (error) => {
  333. error.config && this.removePending(error.config)
  334. loading && this.closeLoading(loading)
  335. //刷新token
  336. if (login && error?.response?.status === 401) {
  337. return this.refreshToken(error.config)
  338. }
  339. //错误处理
  340. if (showErrorMessage) {
  341. this.errorHandle(error)
  342. }
  343. return Promise.reject(error)
  344. }
  345. )
  346. return this.instance
  347. .request({
  348. ...requestParams,
  349. headers: {
  350. ...(requestParams.headers || {}),
  351. ...(type && type !== ContentType.FormData ? { 'Content-Type': type } : {}),
  352. } as RawAxiosRequestHeaders,
  353. params: query,
  354. responseType: responseFormat,
  355. data: body,
  356. url: path,
  357. })
  358. .then((response) => response.data)
  359. }
  360. }