Ben Lin
2024-08-20 2e2ec72bdefad3ff51c786721f11b0d8b82d8b1b
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
61
62
63
64
65
66
67
68
69
70
71
import { ref, watch } from 'vue';
 
import type { UseRequestPlugin, UseRequestTimeout } from '../types';
import { isDocumentVisible } from '../utils/isDocumentVisible';
import subscribeReVisible from '../utils/subscribeReVisible';
 
const usePollingPlugin: UseRequestPlugin<any, any[]> = (
  fetchInstance,
  { pollingInterval, pollingWhenHidden = true, pollingErrorRetryCount = -1 },
) => {
  const timerRef = ref<UseRequestTimeout>();
  const unsubscribeRef = ref<() => void>();
  const countRef = ref<number>(0);
 
  const stopPolling = () => {
    if (timerRef.value) {
      clearTimeout(timerRef.value);
    }
    unsubscribeRef.value?.();
  };
 
  watch(
    () => pollingInterval,
    () => {
      if (!pollingInterval) {
        stopPolling();
      }
    },
  );
 
  if (!pollingInterval) {
    return {};
  }
 
  return {
    onBefore: () => {
      stopPolling();
    },
    onError: () => {
      countRef.value += 1;
    },
    onSuccess: () => {
      countRef.value = 0;
    },
    onFinally: () => {
      if (
        pollingErrorRetryCount === -1 ||
        // When an error occurs, the request is not repeated after pollingErrorRetryCount retries
        (pollingErrorRetryCount !== -1 && countRef.value <= pollingErrorRetryCount)
      ) {
        timerRef.value = setTimeout(() => {
          // if pollingWhenHidden = false && document is hidden, then stop polling and subscribe revisible
          if (!pollingWhenHidden && !isDocumentVisible()) {
            unsubscribeRef.value = subscribeReVisible(() => {
              fetchInstance.refresh();
            });
          } else {
            fetchInstance.refresh();
          }
        }, pollingInterval);
      } else {
        countRef.value = 0;
      }
    },
    onCancel: () => {
      stopPolling();
    },
  };
};
 
export default usePollingPlugin;