Function: getCachedOrFetch()
getCachedOrFetch<
T
>(cache
:TypedCache
<string
,T
>,key
:string
,fetcher
: () =>Promise
<T
>,ttl?
:number
):Promise
<T
>
Defined in: src/utils/cache.ts:416
Retrieve a value from a cache or compute and store it on a cache miss.
Type Parametersโ
Tโ
T
Type of the cached value.
Parametersโ
cacheโ
TypedCache
<string
, T
>
Cache instance to use for lookup and storage.
keyโ
string
Cache key to look up.
fetcherโ
() => Promise
<T
>
Async function that computes or fetches the value on a cache miss.
ttl?โ
number
Optional per-entry TTL in milliseconds to apply when storing the fetched value; when omitted the cache's default TTL (if any) applies.
Returnsโ
Promise
<T
>
A promise that resolves to the cached or freshly fetched value.
Remarksโ
The function first attempts to read from the supplied TypedCache. If
the key is absent or expired it invokes fetcher
to obtain the value, stores
the result in the cache (honoring an optional ttl
), and returns the value.
Any exception thrown by fetcher
is propagated to the caller and no value is
cached in that case.
Exampleโ
const value = await getCachedOrFetch(
AppCaches.general,
"user:123",
async () => {
const resp = await apiClient.get("/user/123");
return resp.data;
},
60_000
);
Throwsโ
Any error thrown by fetcher
is propagated to the caller.