axiosCancel.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import type { AxiosRequestConfig, Canceler } from 'axios';
  2. import axios from 'axios';
  3. import { isFunction } from '/@/utils/is';
  4. // Used to store the identification and cancellation function of each request
  5. let pendingMap = new Map<string, Canceler>();
  6. export const getPendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&');
  7. export class AxiosCanceler {
  8. /**
  9. * Add request
  10. * @param {Object} config
  11. */
  12. addPending(config: AxiosRequestConfig) {
  13. this.removePending(config);
  14. const url = getPendingUrl(config);
  15. config.cancelToken =
  16. config.cancelToken ||
  17. new axios.CancelToken((cancel) => {
  18. if (!pendingMap.has(url)) {
  19. // If there is no current request in pending, add it
  20. pendingMap.set(url, cancel);
  21. }
  22. });
  23. }
  24. /**
  25. * @description: Clear all pending
  26. */
  27. removeAllPending() {
  28. pendingMap.forEach((cancel) => {
  29. cancel && isFunction(cancel) && cancel();
  30. });
  31. pendingMap.clear();
  32. }
  33. /**
  34. * Removal request
  35. * @param {Object} config
  36. */
  37. removePending(config: AxiosRequestConfig) {
  38. const url = getPendingUrl(config);
  39. if (pendingMap.has(url)) {
  40. // If there is a current request identifier in pending,
  41. // the current request needs to be cancelled and removed
  42. const cancel = pendingMap.get(url);
  43. cancel && cancel(url);
  44. pendingMap.delete(url);
  45. }
  46. }
  47. /**
  48. * @description: reset
  49. */
  50. reset(): void {
  51. pendingMap = new Map<string, Canceler>();
  52. }
  53. }