YangYuGang
2025-03-11 7462fd192326d7cf3418b6185ca437b2667cbeab
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
import { ref } from 'vue';
 
import type { UseRequestPlugin, UseRequestTimeout } from '../types';
 
const useRetryPlugin: UseRequestPlugin<any, any[]> = (
  fetchInstance,
  { retryInterval, retryCount },
) => {
  const timerRef = ref<UseRequestTimeout>();
  const countRef = ref(0);
 
  const triggerByRetry = ref(false);
 
  if (!retryCount) {
    return {};
  }
 
  return {
    onBefore: () => {
      if (!triggerByRetry.value) {
        countRef.value = 0;
      }
      triggerByRetry.value = false;
 
      if (timerRef.value) {
        clearTimeout(timerRef.value);
      }
    },
    onSuccess: () => {
      countRef.value = 0;
    },
    onError: () => {
      countRef.value += 1;
      if (retryCount === -1 || countRef.value <= retryCount) {
        // Exponential backoff
        const timeout = retryInterval ?? Math.min(1000 * 2 ** countRef.value, 30000);
        timerRef.value = setTimeout(() => {
          triggerByRetry.value = true;
          fetchInstance.refresh();
        }, timeout);
      } else {
        countRef.value = 0;
      }
    },
    onCancel: () => {
      countRef.value = 0;
      if (timerRef.value) {
        clearTimeout(timerRef.value);
      }
    },
  };
};
 
export default useRetryPlugin;