@apislash/cache
v1.0.0
Published
TTL cache with stale-while-revalidate for any TypeScript project — pluggable backend (in-memory included), framework-agnostic. Published by Apislash.
Readme
@apislash/cache
TTL cache with stale-while-revalidate for any TypeScript project. A small, framework-agnostic caching layer with a pluggable backend (in-memory included) — return cached data instantly, serve stale while revalidating in the background, and refetch when the stale window expires.
Generic and usable in any app; published and maintained by Apislash (offered to customers under the Apislash brand). MIT licensed.
Install
npm install @apislash/cacheUsage
import { CacheClient, MemoryCacheBackend } from "@apislash/cache";
const cache = new CacheClient(new MemoryCacheBackend(), {
ttlMs: 60_000, // fresh for 60s
staleWhileRevalidateMs: 300_000, // serve stale up to 5 min while revalidating
});
const { data, stale, fromCache } = await cache.get("user:42", () => fetchUser(42));
await cache.invalidate("user:42");
await cache.clear();get(key, fetcher, opts?) returns { data, stale, fromCache }: a cold miss calls the fetcher and stores the result; a warm hit returns instantly; once the TTL passes (but within the stale window) it returns the stale value and revalidates in the background.
Backends
CacheBackend is a simple get / set / delete / clear interface. MemoryCacheBackend is included; bring your own (Redis, a KV store, or @apislash/storage) by implementing the interface.
License
MIT © Apislash
