(
fetchInstance,
{
cacheKey,
cacheTime = 5 * 60 * 1000,
staleTime = 0,
setCache: customSetCache,
getCache: customGetCache,
},
)
| 8 | import { trigger, subscribe } from '../utils/cacheSubscribe'; |
| 9 | |
| 10 | const useCachePlugin: Plugin<any, any[]> = ( |
| 11 | fetchInstance, |
| 12 | { |
| 13 | cacheKey, |
| 14 | cacheTime = 5 * 60 * 1000, |
| 15 | staleTime = 0, |
| 16 | setCache: customSetCache, |
| 17 | getCache: customGetCache, |
| 18 | }, |
| 19 | ) => { |
| 20 | const unSubscribeRef = useRef<() => void>(undefined); |
| 21 | |
| 22 | const currentPromiseRef = useRef<Promise<any>>(undefined); |
| 23 | |
| 24 | const _setCache = (key: string, cachedData: CachedData) => { |
| 25 | if (customSetCache) { |
| 26 | customSetCache(cachedData); |
| 27 | } else { |
| 28 | setCache(key, cacheTime, cachedData); |
| 29 | } |
| 30 | trigger(key, cachedData.data); |
| 31 | }; |
| 32 | |
| 33 | const _getCache = (key: string, params: any[] = []) => { |
| 34 | if (customGetCache) { |
| 35 | return customGetCache(params); |
| 36 | } |
| 37 | return getCache(key); |
| 38 | }; |
| 39 | |
| 40 | useCreation(() => { |
| 41 | if (!cacheKey) { |
| 42 | return; |
| 43 | } |
| 44 | |
| 45 | // get data from cache when init |
| 46 | const cacheData = _getCache(cacheKey); |
| 47 | if (cacheData && Object.hasOwnProperty.call(cacheData, 'data')) { |
| 48 | fetchInstance.state.data = cacheData.data; |
| 49 | fetchInstance.state.params = cacheData.params; |
| 50 | if (staleTime === -1 || Date.now() - cacheData.time <= staleTime) { |
| 51 | fetchInstance.state.loading = false; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // subscribe same cachekey update, trigger update |
| 56 | unSubscribeRef.current = subscribe(cacheKey, (data) => { |
| 57 | fetchInstance.setState({ data }); |
| 58 | }); |
| 59 | }, []); |
| 60 | |
| 61 | useUnmount(() => { |
| 62 | unSubscribeRef.current?.(); |
| 63 | }); |
| 64 | |
| 65 | if (!cacheKey) { |
| 66 | return {}; |
| 67 | } |
nothing calls this directly
no test coverage detected
searching dependent graphs…