http-client.ejs 12 KB

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