Ben Lin
2024-06-23 200eb764e83c7a77defeaf98130801d300dbee5d
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
import type { DebouncedFunc, ThrottleSettings } from 'lodash-es';
import { throttle } from 'lodash-es';
import { ref, watchEffect } from 'vue';
 
import type { UseRequestPlugin } from '../types';
 
const useThrottlePlugin: UseRequestPlugin<any, any[]> = (
  fetchInstance,
  { throttleWait, throttleLeading, throttleTrailing },
) => {
  const throttledRef = ref<DebouncedFunc<any>>();
 
  const options: ThrottleSettings = {};
  if (throttleLeading !== undefined) {
    options.leading = throttleLeading;
  }
  if (throttleTrailing !== undefined) {
    options.trailing = throttleTrailing;
  }
 
  watchEffect(() => {
    if (throttleWait) {
      const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
 
      throttledRef.value = throttle(
        (callback) => {
          callback();
        },
        throttleWait,
        options,
      );
 
      // throttle runAsync should be promise
      // https://github.com/lodash/lodash/issues/4400#issuecomment-834800398
      fetchInstance.runAsync = (...args) => {
        return new Promise((resolve, reject) => {
          throttledRef.value?.(() => {
            _originRunAsync(...args)
              .then(resolve)
              .catch(reject);
          });
        });
      };
 
      return () => {
        fetchInstance.runAsync = _originRunAsync;
        throttledRef.value?.cancel();
      };
    }
  });
 
  if (!throttleWait) {
    return {};
  }
 
  return {
    onCancel: () => {
      throttledRef.value?.cancel();
    },
  };
};
 
export default useThrottlePlugin;