Ben Lin
2024-12-26 056f7fd796fcbb4f0383db72795f99007b8749ef
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
import { onUnmounted, ref, watchEffect } from 'vue';
 
import type { UseRequestPlugin } from '../types';
import { limit } from '../utils/limit';
import subscribeFocus from '../utils/subscribeFocus';
 
const useRefreshOnWindowFocusPlugin: UseRequestPlugin<any, any[]> = (
  fetchInstance,
  { refreshOnWindowFocus, focusTimespan = 5000 },
) => {
  const unsubscribeRef = ref<() => void>();
 
  const stopSubscribe = () => {
    unsubscribeRef.value?.();
  };
 
  watchEffect(() => {
    if (refreshOnWindowFocus) {
      const limitRefresh = limit(fetchInstance.refresh.bind(fetchInstance), focusTimespan);
      unsubscribeRef.value = subscribeFocus(() => {
        limitRefresh();
      });
    }
 
    return () => {
      stopSubscribe();
    };
  });
 
  onUnmounted(() => {
    stopSubscribe();
  });
 
  return {};
};
 
export default useRefreshOnWindowFocusPlugin;