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