Blame view

src/utils/http/axios/axiosCancel.ts 1.49 KB
陈文彬 authored
1
2
3
4
5
import type { AxiosRequestConfig, Canceler } from 'axios';
import axios from 'axios';

import { isFunction } from '/@/utils/is';
Vben authored
6
// Used to store the identification and cancellation function of each request
陈文彬 authored
7
8
9
10
11
12
let pendingMap = new Map<string, Canceler>();

export const getPendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&');

export class AxiosCanceler {
  /**
Vben authored
13
   * Add request
陈文彬 authored
14
15
16
17
18
19
20
21
22
   * @param {Object} config
   */
  addPending(config: AxiosRequestConfig) {
    this.removePending(config);
    const url = getPendingUrl(config);
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!pendingMap.has(url)) {
Vben authored
23
          // If there is no current request in pending, add it
陈文彬 authored
24
25
26
27
28
29
          pendingMap.set(url, cancel);
        }
      });
  }

  /**
Vben authored
30
   * @description: Clear all pending
陈文彬 authored
31
32
33
34
35
36
37
38
39
   */
  removeAllPending() {
    pendingMap.forEach((cancel) => {
      cancel && isFunction(cancel) && cancel();
    });
    pendingMap.clear();
  }

  /**
Vben authored
40
   * Removal request
陈文彬 authored
41
42
43
44
45
46
   * @param {Object} config
   */
  removePending(config: AxiosRequestConfig) {
    const url = getPendingUrl(config);

    if (pendingMap.has(url)) {
Vben authored
47
48
      // If there is a current request identifier in pending,
      // the current request needs to be cancelled and removed
陈文彬 authored
49
50
51
52
53
54
55
      const cancel = pendingMap.get(url);
      cancel && cancel(url);
      pendingMap.delete(url);
    }
  }

  /**
Vben authored
56
   * @description: reset
陈文彬 authored
57
58
59
60
61
   */
  reset(): void {
    pendingMap = new Map<string, Canceler>();
  }
}