http-client.ejs 12 KB

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