http-client.ejs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. <%
  2. const { apiConfig, generateResponses, config } = it;
  3. %>
  4. import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, HeadersDefaults, ResponseType } 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. },
  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 })
  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. return new Promise((resolve) => {
  194. window.requests.push(() => {
  195. resolve(this.instance(config))
  196. })
  197. })
  198. }
  199. window.tokenRefreshing = true
  200. return this.request<AxiosResponse, any>({
  201. path: `/api/admin/auth/refresh`,
  202. method: 'GET',
  203. secure: true,
  204. format: 'json',
  205. login: false,
  206. query: {
  207. token: token,
  208. },
  209. })
  210. .then((res) => {
  211. if (res?.success) {
  212. const token = res.data.token
  213. setToken(token)
  214. window.requests.forEach((apiRequest) => apiRequest())
  215. window.requests = []
  216. return this.instance(config)
  217. } else {
  218. clearToken()
  219. return Promise.reject(res)
  220. }
  221. })
  222. .catch((error) => {
  223. clearToken()
  224. return Promise.reject(error)
  225. })
  226. .finally(() => {
  227. window.tokenRefreshing = false
  228. })
  229. }
  230. /**
  231. * 储存每个请求的唯一cancel回调, 以此为标识
  232. */
  233. protected addPending(config: AxiosRequestConfig) {
  234. const pendingKey = this.getPendingKey(config)
  235. config.cancelToken =
  236. config.cancelToken ||
  237. new axios.CancelToken((cancel) => {
  238. if (!pendingMap.has(pendingKey)) {
  239. pendingMap.set(pendingKey, cancel)
  240. }
  241. })
  242. }
  243. /**
  244. * 删除重复的请求
  245. */
  246. protected removePending(config: AxiosRequestConfig) {
  247. const pendingKey = this.getPendingKey(config)
  248. if (pendingMap.has(pendingKey)) {
  249. const cancelToken = pendingMap.get(pendingKey)
  250. cancelToken(pendingKey)
  251. pendingMap.delete(pendingKey)
  252. }
  253. }
  254. /**
  255. * 生成每个请求的唯一key
  256. */
  257. protected getPendingKey(config: AxiosRequestConfig) {
  258. let { data } = config
  259. const { url, method, params, headers } = config
  260. if (typeof data === 'string') data = JSON.parse(data)
  261. return [url, method, headers && headers.Authorization ? headers.Authorization : '', JSON.stringify(params), JSON.stringify(data)].join('&')
  262. }
  263. /**
  264. * 关闭Loading层实例
  265. */
  266. protected closeLoading(loading: boolean = false) {
  267. if (loading && loadingInstance.count > 0) loadingInstance.count--
  268. if (loadingInstance.count === 0) {
  269. loadingInstance.target.close()
  270. loadingInstance.target = null
  271. }
  272. }
  273. public request = async <T = any, _E = any>({
  274. secure,
  275. path,
  276. type,
  277. query,
  278. format,
  279. body,
  280. showErrorMessage = true,
  281. showSuccessMessage = false,
  282. login = true,
  283. loading = false,
  284. loadingOptions = {},
  285. cancelRepeatRequest = false,
  286. ...params
  287. <% if (config.unwrapResponseData) { %>
  288. }: FullRequestParams): Promise<T> => {
  289. <% } else { %>
  290. }: FullRequestParams): Promise<AxiosResponse<T>> => {
  291. <% } %>
  292. const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
  293. const requestParams = this.mergeRequestParams(params, secureParams);
  294. const responseFormat = (format || this.format) || undefined;
  295. if (type === ContentType.FormData && body && body !== null && typeof body === "object") {
  296. body = this.createFormData(body as Record<string, unknown>);
  297. }
  298. if (type === ContentType.Text && body && body !== null && typeof body !== "string") {
  299. body = JSON.stringify(body);
  300. }
  301. // 请求拦截
  302. this.instance.interceptors.request.use(
  303. (config) => {
  304. this.removePending(config)
  305. cancelRepeatRequest && this.addPending(config)
  306. if (loading) {
  307. loadingInstance.count++
  308. if (loadingInstance.count === 1) {
  309. loadingInstance.target = ElLoading.service(loadingOptions)
  310. }
  311. }
  312. const accessToken = getToken()
  313. config.headers!['Authorization'] = `Bearer ${accessToken}`
  314. return config
  315. },
  316. (error) => {
  317. return Promise.reject(error)
  318. }
  319. )
  320. // 响应拦截
  321. this.instance.interceptors.response.use(
  322. (res) => {
  323. this.removePending(res.config)
  324. loading && this.closeLoading(loading)
  325. const data = res.data
  326. if (data.success) {
  327. if (showSuccessMessage) {
  328. ElMessage.success({ message: data.msg ? data.msg : '操作成功' })
  329. }
  330. } else {
  331. if (showErrorMessage) {
  332. ElMessage.error({ message: data.msg ? data.msg : '操作失败' })
  333. }
  334. // return Promise.reject(res)
  335. }
  336. return res
  337. },
  338. async (error) => {
  339. error.config && this.removePending(error.config)
  340. loading && this.closeLoading(loading)
  341. //刷新token
  342. if (login && error?.response?.status === 401) {
  343. return this.refreshToken(error.config)
  344. }
  345. //错误处理
  346. if (showErrorMessage) {
  347. this.errorHandle(error)
  348. }
  349. return Promise.reject(error)
  350. }
  351. )
  352. return this.instance.request({
  353. ...requestParams,
  354. headers: {
  355. ...(requestParams.headers || {}),
  356. ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
  357. },
  358. params: query,
  359. responseType: responseFormat,
  360. data: body,
  361. url: path,
  362. <% if (config.unwrapResponseData) { %>
  363. }).then(response => response.data);
  364. <% } else { %>
  365. });
  366. <% } %>
  367. };
  368. }