Sanakey
3 天以前 b5c1614fe473330ceca8b7cff0f1802e19bd5039
提交 | 用户 | age
b14a15 1 import type { AxiosRequestConfig } from 'axios';
2f6253 2
b14a15 3 // 用于存储每个请求的标识和取消函数
KL 4 const pendingMap = new Map<string, AbortController>();
2f6253 5
b14a15 6 const getPendingUrl = (config: AxiosRequestConfig): string => {
KL 7   return [config.method, config.url].join('&');
8 };
2f6253 9
10 export class AxiosCanceler {
11   /**
b14a15 12    * 添加请求
KL 13    * @param config 请求配置
2f6253 14    */
b14a15 15   public addPending(config: AxiosRequestConfig): void {
2f6253 16     this.removePending(config);
17     const url = getPendingUrl(config);
b14a15 18     const controller = new AbortController();
KL 19     config.signal = config.signal || controller.signal;
20     if (!pendingMap.has(url)) {
21       // 如果当前请求不在等待中,将其添加到等待中
22       pendingMap.set(url, controller);
23     }
2f6253 24   }
25
26   /**
b14a15 27    * 清除所有等待中的请求
2f6253 28    */
b14a15 29   public removeAllPending(): void {
KL 30     pendingMap.forEach((abortController) => {
31       if (abortController) {
32         abortController.abort();
33       }
2f6253 34     });
b14a15 35     this.reset();
2f6253 36   }
37
38   /**
b14a15 39    * 移除请求
KL 40    * @param config 请求配置
2f6253 41    */
b14a15 42   public removePending(config: AxiosRequestConfig): void {
2f6253 43     const url = getPendingUrl(config);
44     if (pendingMap.has(url)) {
b14a15 45       // 如果当前请求在等待中,取消它并将其从等待中移除
KL 46       const abortController = pendingMap.get(url);
47       if (abortController) {
48         abortController.abort(url);
49       }
2f6253 50       pendingMap.delete(url);
51     }
52   }
53
54   /**
b14a15 55    * 重置
2f6253 56    */
b14a15 57   public reset(): void {
KL 58     pendingMap.clear();
2f6253 59   }
60 }