http-client.ts 12 KB

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