http-client.ejs 12 KB

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