• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

alibaba / hooks / #49

05 Nov 2025 09:55AM UTC coverage: 85.833% (-0.6%) from 86.39%
#49

push

travis-pro

952 of 1206 branches covered (78.94%)

Branch coverage included in aggregate %.

2241 of 2514 relevant lines covered (89.14%)

84.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.27
/packages/hooks/src/useRequest/src/plugins/useCachePlugin.ts
1
import { useRef } from 'react';
13✔
2
import useCreation from '../../../useCreation';
13✔
3
import useUnmount from '../../../useUnmount';
13✔
4
import type { Plugin } from '../types';
5
import { setCache, getCache } from '../utils/cache';
13✔
6
import type { CachedData } from '../utils/cache';
7
import { setCachePromise, getCachePromise } from '../utils/cachePromise';
13✔
8
import { trigger, subscribe } from '../utils/cacheSubscribe';
13✔
9

10
const useCachePlugin: Plugin<any, any[]> = (
13✔
11
  fetchInstance,
12
  {
13
    cacheKey,
14
    cacheTime = 5 * 60 * 1000,
300✔
15
    staleTime = 0,
292✔
16
    setCache: customSetCache,
17
    getCache: customGetCache,
18
  },
19
) => {
20
  const unSubscribeRef = useRef<() => void>(undefined);
308✔
21

22
  const currentPromiseRef = useRef<Promise<any>>(undefined);
308✔
23

24
  const _setCache = (key: string, cachedData: CachedData) => {
308✔
25
    if (customSetCache) {
12✔
26
      customSetCache(cachedData);
2✔
27
    } else {
28
      setCache(key, cacheTime, cachedData);
10✔
29
    }
30
    trigger(key, cachedData.data);
12✔
31
  };
32

33
  const _getCache = (key: string, params: any[] = []) => {
308✔
34
    if (customGetCache) {
32✔
35
      return customGetCache(params);
4✔
36
    }
37
    return getCache(key);
28✔
38
  };
39

40
  useCreation(() => {
308✔
41
    if (!cacheKey) {
72✔
42
      return;
57✔
43
    }
44

45
    // get data from cache when init
46
    const cacheData = _getCache(cacheKey);
15✔
47
    if (cacheData && Object.hasOwnProperty.call(cacheData, 'data')) {
15✔
48
      fetchInstance.state.data = cacheData.data;
6✔
49
      fetchInstance.state.params = cacheData.params;
6✔
50
      if (staleTime === -1 || Date.now() - cacheData.time <= staleTime) {
6✔
51
        fetchInstance.state.loading = false;
2✔
52
      }
53
    }
54

55
    // subscribe same cachekey update, trigger update
56
    unSubscribeRef.current = subscribe(cacheKey, (data) => {
15✔
57
      fetchInstance.setState({ data });
×
58
    });
59
  }, []);
60

61
  useUnmount(() => {
308✔
62
    unSubscribeRef.current?.();
72✔
63
  });
64

65
  if (!cacheKey) {
308✔
66
    return {};
261✔
67
  }
68

69
  return {
47✔
70
    onBefore: (params) => {
71
      const cacheData = _getCache(cacheKey, params);
17✔
72

73
      if (!cacheData || !Object.hasOwnProperty.call(cacheData, 'data')) {
17✔
74
        return {};
10✔
75
      }
76

77
      // If the data is fresh, stop request
78
      if (staleTime === -1 || Date.now() - cacheData.time <= staleTime) {
7✔
79
        return {
3✔
80
          loading: false,
81
          data: cacheData?.data,
9!
82
          error: undefined,
83
          returnNow: true,
84
        };
85
      } else {
86
        // If the data is stale, return data, and request continue
87
        return {
4✔
88
          data: cacheData?.data,
12!
89
          error: undefined,
90
        };
91
      }
92
    },
93
    onRequest: (service, args) => {
94
      let servicePromise = getCachePromise(cacheKey);
14✔
95

96
      // If has servicePromise, and is not trigger by self, then use it
97
      if (servicePromise && servicePromise !== currentPromiseRef.current) {
14✔
98
        return { servicePromise };
1✔
99
      }
100

101
      servicePromise = service(...args);
13✔
102
      currentPromiseRef.current = servicePromise;
13✔
103
      setCachePromise(cacheKey, servicePromise);
13✔
104
      return { servicePromise };
13✔
105
    },
106
    onSuccess: (data, params) => {
107
      if (cacheKey) {
11✔
108
        // cancel subscribe, avoid trgger self
109
        unSubscribeRef.current?.();
11!
110
        _setCache(cacheKey, {
11✔
111
          data,
112
          params,
113
          time: Date.now(),
114
        });
115
        // resubscribe
116
        unSubscribeRef.current = subscribe(cacheKey, (d) => {
11✔
117
          fetchInstance.setState({ data: d });
×
118
        });
119
      }
120
    },
121
    onMutate: (data) => {
122
      if (cacheKey) {
1✔
123
        // cancel subscribe, avoid trigger self
124
        unSubscribeRef.current?.();
1!
125
        _setCache(cacheKey, {
1✔
126
          data,
127
          params: fetchInstance.state.params,
128
          time: Date.now(),
129
        });
130
        // resubscribe
131
        unSubscribeRef.current = subscribe(cacheKey, (d) => {
1✔
132
          fetchInstance.setState({ data: d });
×
133
        });
134
      }
135
    },
136
  };
137
};
138

139
export default useCachePlugin;
13✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc