createCache
function createCache(options): Cache;Defined in: unstorage-utils.ts:181
Create a reusable cache instance that can be used as a decorator or wrapper.
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.
Parameters
Section titled “Parameters”| Parameter | Type |
|---|---|
options |
CacheOptions |
Returns
Section titled “Returns”Examples
Section titled “Examples”As decorator
const cache = createCache({ storage: createStorage(), prefix: "api", ttl: 60 });
class UserService { @cache.decorator async getUser(id: string) { return db.users.findById(id); }
@cache.decorator({ ttl: 300 }) async getProfile(id: string, lang: string) { return db.profiles.find(id, lang); }}As wrapper
const cache = createCache({ storage, prefix: "api", ttl: 60 });// Each wrapped function gets its own keys: the two never share entries.const loadUser = cache.wrap(async (id: string, role: string) => fetchUser(id, role));const loadPlan = cache.wrap(async (id: string) => billing.plan(id), { ttl: 600 });