Line data Source code
1 : import QuickLRU from '@alloc/quick-lru'
2 :
3 : import { paramsToCacheKey } from '@/utils/formatUtil'
4 :
5 2356 : const DEFAULT_MAX_SIZE = 50
6 :
7 : interface CachedRequestOptions {
8 : /**
9 : * Maximum number of items to store in the cache
10 : * @default 50
11 : */
12 : maxSize?: number
13 : /**
14 : * Function to generate a cache key from parameters
15 : */
16 : cacheKeyFn?: (params: unknown) => string
17 : }
18 :
19 : /**
20 : * Composable that wraps a function with memoization, request deduplication, and abort handling.
21 : */
22 18840 : export function useCachedRequest<TParams, TResult>(
23 : requestFunction: (
24 : params: TParams,
25 : signal?: AbortSignal
26 : ) => Promise<TResult | null>,
27 : options: CachedRequestOptions = {}
28 : ) {
29 18840 : const { maxSize = DEFAULT_MAX_SIZE, cacheKeyFn = paramsToCacheKey } = options
30 :
31 18840 : const cache = new QuickLRU<string, TResult | null>({ maxSize })
32 18840 : const pendingRequests = new Map<string, Promise<TResult | null>>()
33 18840 : const abortControllers = new Map<string, AbortController>()
34 :
35 18840 : const executeAndCacheCall = async (
36 : params: TParams,
37 : cacheKey: string
38 : ): Promise<TResult | null> => {
39 88 : try {
40 88 : const controller = new AbortController()
41 88 : abortControllers.set(cacheKey, controller)
42 :
43 88 : const responsePromise = requestFunction(params, controller.signal)
44 88 : pendingRequests.set(cacheKey, responsePromise)
45 :
46 88 : const result = await responsePromise
47 88 : cache.set(cacheKey, result)
48 :
49 88 : return result
50 : } catch {
51 0 : cache.set(cacheKey, null)
52 0 : return null
53 : } finally {
54 88 : pendingRequests.delete(cacheKey)
55 88 : abortControllers.delete(cacheKey)
56 : }
57 : }
58 :
59 18840 : const handlePendingRequest = async (
60 : pendingRequest: Promise<TResult | null>
61 : ): Promise<TResult | null> => {
62 4 : try {
63 4 : return await pendingRequest
64 : } catch (err) {
65 0 : console.error('Error in pending request:', err)
66 0 : return null
67 : }
68 : }
69 :
70 18840 : const abortAllRequests = () => {
71 17 : for (const controller of abortControllers.values()) {
72 3 : controller.abort()
73 : }
74 : }
75 :
76 18840 : const cancel = () => {
77 17 : abortAllRequests()
78 17 : abortControllers.clear()
79 17 : pendingRequests.clear()
80 : }
81 :
82 18840 : const call = async (params: TParams): Promise<TResult | null> => {
83 179 : const cacheKey = cacheKeyFn(params)
84 :
85 179 : const cachedResult = cache.get(cacheKey)
86 179 : if (cachedResult !== undefined) return cachedResult
87 :
88 92 : const pendingRequest = pendingRequests.get(cacheKey)
89 179 : if (pendingRequest) return handlePendingRequest(pendingRequest)
90 :
91 88 : return executeAndCacheCall(params, cacheKey)
92 : }
93 :
94 18840 : return {
95 : call,
96 : cancel,
97 : clear: () => cache.clear(),
98 : evict: (params: TParams) => {
99 1 : cache.delete(cacheKeyFn(params))
100 : }
101 : }
102 : }
|