Basic Usage
@mongez/cache — Basic Usage
How to use
Prerequisites
The driver must be configured before any cache call. See the drivers skill for the full bootstrap. Minimal example:
import cache, { PlainLocalStorageDriver, setCacheConfigurations } from "@mongez/cache";
setCacheConfigurations({ driver: new PlainLocalStorageDriver() });set
cache.set(key: string, value: any, expiresAfter?: number): CacheManagerkey— bare string; prefix (if configured) is prepended automatically.value— any JSON-serializable type: string, number, boolean, array, plain object.expiresAfter— optional TTL in seconds. Overrides any globalexpiresAfterfrom config. Omit for no expiry (or to fall back to the global default).
cache.set("user", { id: 1, name: "Hasan" });cache.set("letters", ["a", "b", "c"]);cache.set("token", "abc123", 60 * 15); // expires in 15 minutescache.set("session", value, 0); // 0 = no expiry (falsy disables TTL)Returns this (chainable), though chaining is rarely needed.
get
cache.get(key: string, defaultValue?: any): any- Returns the stored value, or
defaultValue(defaults tonull) when the key does not exist or has expired. - Expired entries are deleted from storage on read and the default value is returned.
cache.get("user"); // { id: 1, name: "Hasan" }cache.get("ghost"); // nullcache.get("ghost", "fallback"); // "fallback"has
cache.has(key: string): booleanReturns true if the raw storage entry exists (note: does not check expiry — the expiry check happens in get). Use get(key) !== null when you need a definitive existence-and-not-expired check.
cache.has("user"); // truecache.has("ghost"); // falseremove
cache.remove(key: string): CacheManagerDeletes a single key from storage.
cache.remove("token");clear
cache.clear(): CacheManagerWipes the entire backing store. For PlainLocalStorageDriver this calls localStorage.clear() — all keys, including those not managed by this package, are removed. Use with care in multi-library setups.
cache.clear();Per-call TTL vs. global default TTL
// Global default: every write that omits a TTL expires in 1 hoursetCacheConfigurations({ driver: new PlainLocalStorageDriver(), expiresAfter: 60 * 60,});
cache.set("user", payload); // expires in 1 hour (global default)cache.set("refresh", token, 60 * 5); // expires in 5 minutes (overrides global)cache.set("static", data, 0); // no expiry (0 is falsy — disables TTL for this entry)Key prefixing
Prefix is prepended to the raw storage key automatically. You always work with the bare key:
setCacheConfigurations({ driver: new PlainLocalStorageDriver(), prefix: "shop-",});
cache.set("user", { id: 1 });// Stored in localStorage as: "shop-user"
cache.get("user"); // reads "shop-user" — prefix handled internallycache.remove("user"); // deletes "shop-user"Prefixes prevent key collisions between apps sharing the same domain.
Wiring to @mongez/atom persist slot
@mongez/atom accepts a persist adapter that must implement { get, set, remove }. The cache manager’s shape is compatible with a thin wrapper (wrapper exists because set on the driver returns this, but atoms expect void):
import { createAtom } from "@mongez/atom";import cache from "@mongez/cache";
const userAtom = createAtom({ key: "auth.user", default: { name: "Anon" }, persist: { get: (key) => cache.get(key), set: (key, value) => { cache.set(key, value); }, remove: (key) => { cache.remove(key); }, },});For a shared adapter used across many atoms, extract it to a module:
import cache from "@mongez/cache";
export const cacheAdapter = { get: (key: string) => cache.get(key), set: (key: string, value: unknown) => { cache.set(key, value); }, remove: (key: string) => { cache.remove(key); },};import { cacheAdapter } from "./adapters/cacheAdapter";
const themeAtom = createAtom({ key: "ui.theme", default: "light", persist: cacheAdapter });const langAtom = createAtom({ key: "ui.lang", default: "en", persist: cacheAdapter });Reading config at runtime
import { getCacheConfigurations, getCacheConfig } from "@mongez/cache";
getCacheConfigurations(); // full CacheConfigurations objectgetCacheConfig("expiresAfter"); // e.g. 3600getCacheConfig("prefix"); // e.g. "shop-"Key details / Pitfalls
getreturnsnull(notundefined) as the default. Pass an explicit second argument when you need a different sentinel value.- Expired entries are cleaned up lazily on
get.hasdoes not check expiry. A key can returntruefromhasbut return the default value fromgetwhen the entry has expired. clear()wipes the entire storage backend. ForPlainLocalStorageDriver, this includes keys written by other libraries or browser extensions stored inlocalStorage. Preferremovefor targeted cleanup.- TTL
0disables expiry for that entry (falsy check). UseexpiresAfter: 1as the minimum if you want a near-immediate expiry. - Values must survive JSON round-trips.
Map,Set,Date,BigInt, class instances, and circular references will not survive the default serializer. Use a customvalueConverter/valuePareror serialize before storing. - The
setreturn value is chainable but the chain type isany. TypeScript will not catch method calls aftercache.set(...)in a chain. Prefer standalone statements.