http-client.ejs 12 KB

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