Blame view

src/utils/http/axios/axiosCancel.ts 1.46 KB
1
import type { AxiosRequestConfig } from 'axios';
陈文彬 authored
2
3
4
// 用于存储每个请求的标识和取消函数
const pendingMap = new Map<string, AbortController>();
陈文彬 authored
5
6
7
8
const getPendingUrl = (config: AxiosRequestConfig): string => {
  return [config.method, config.url].join('&');
};
陈文彬 authored
9
10
11

export class AxiosCanceler {
  /**
12
13
   * 添加请求
   * @param config 请求配置
陈文彬 authored
14
   */
15
  public addPending(config: AxiosRequestConfig): void {
陈文彬 authored
16
17
    this.removePending(config);
    const url = getPendingUrl(config);
18
19
20
21
22
23
    const controller = new AbortController();
    config.signal = config.signal || controller.signal;
    if (!pendingMap.has(url)) {
      // 如果当前请求不在等待中,将其添加到等待中
      pendingMap.set(url, controller);
    }
陈文彬 authored
24
25
26
  }

  /**
27
   * 清除所有等待中的请求
陈文彬 authored
28
   */
29
30
31
32
33
  public removeAllPending(): void {
    pendingMap.forEach((abortController) => {
      if (abortController) {
        abortController.abort();
      }
陈文彬 authored
34
    });
35
    this.reset();
陈文彬 authored
36
37
38
  }

  /**
39
40
   * 移除请求
   * @param config 请求配置
陈文彬 authored
41
   */
42
  public removePending(config: AxiosRequestConfig): void {
陈文彬 authored
43
44
    const url = getPendingUrl(config);
    if (pendingMap.has(url)) {
45
46
47
48
49
      // 如果当前请求在等待中,取消它并将其从等待中移除
      const abortController = pendingMap.get(url);
      if (abortController) {
        abortController.abort(url);
      }
陈文彬 authored
50
51
52
53
54
      pendingMap.delete(url);
    }
  }

  /**
55
   * 重置
陈文彬 authored
56
   */
57
58
  public reset(): void {
    pendingMap.clear();
陈文彬 authored
59
60
  }
}