withCache
function withCache<TArgs, TResult>(fn, options): (...args) => Promise<TResult>;Defined in: unstorage-utils.ts:102
Wrap an async function with a persistent cache layer backed by unstorage. Supports functions with any number of arguments.
A plain TTL cache, kept small on purpose: no stale-while-revalidate, and
concurrent misses for the same key each call the function. When you need
those, use @epic-web/cachified
(stale-while-revalidate, value validation, one fetch per key for concurrent
misses) or bentocache (multi-tier cache with
stampede protection and grace periods); see the recommended libraries.
Type Parameters
Section titled “Type Parameters”| Type Parameter |
|---|
TArgs extends unknown[] |
TResult extends StorageValue |
Parameters
Section titled “Parameters”| Parameter | Type |
|---|---|
fn |
(…args) => Promise<TResult> |
options |
WithCacheOptions<TArgs> |
Returns
Section titled “Returns”(…args) => Promise<TResult>
Examples
Section titled “Examples”Single arg
const loadUser = withCache( async (id: string) => db.users.findById(id), { storage: createStorage(), prefix: "user", ttl: 60 },);await loadUser("user_123");Multiple args
const search = withCache( async (query: string, page: number) => api.search(query, page), { storage, prefix: "search", ttl: 300 },);await search("hello", 1);Custom toKey
const loadUser = withCache( async (id: string, role: string) => fetchUser(id, role), { storage, prefix: "user", toKey: (id) => id },);