@toapi/cache
@toapi/cache is a cache library built around tag-based invalidation. Instead of expiring individual keys, you invalidate entire groups of cache entries by their tags — a pattern that maps naturally to how data actually changes in real applications.
It is the reference cache implementation for the Toapi stack and is usually used to add caching to @toapi/server.
Installation
Section titled “Installation”npm install @toapi/cacheThe Redis and Postgres backends need an extra peer dependency (@redis/client or pg respectively). Both are optional — install only the one you use.
Backends
Section titled “Backends”All backends implement the same Cache interface, so you can swap between them without touching application code.
InMemoryCache— SQLite in-memory database. Fast, zero I/O — ideal for development, testing, and single-process deployments.FilesystemCache— SQLite file-based database. Survives process restarts, suitable for single-host production setups.RedisCache— Redis-backed distributed cache with pub/sub support. The right choice for multi-host deployments.PostgresCache— PostgreSQL-backed distributed cache usingLISTEN/NOTIFY. For multi-host deployments that already run Postgres and would rather not add Redis.
Quick Start
Section titled “Quick Start”import { InMemoryCache } from "@toapi/cache/in-memory-cache";
const cache = new InMemoryCache();
// Store with tagsawait cache.set({ key: "user:1", data: { name: "Alice" }, ttl: 3600, tags: ["users", "user:1"],});
// Retrieveconst entry = await cache.get("user:1");// { data: { name: "Alice" }, attachment: null }
// Invalidate all entries tagged "users"await cache.delete(["users"]);
await cache.get("user:1"); // nullUsage with Toapi
Section titled “Usage with Toapi”Pass a cache instance to createRequestHandler to enable server-side caching:
import { createRequestHandler } from "@toapi/server";import { InMemoryCache } from "@toapi/cache/in-memory-cache";
const cache = new InMemoryCache();const handleRequest = createRequestHandler(api, { cache });See Caching for the full picture.
Reference
Section titled “Reference”- Cache Interface — the shared interface all backends implement.
- InMemoryCache — SQLite in-memory backend.
- FilesystemCache — SQLite file-based backend.
- RedisCache — Redis-backed distributed backend.
- PostgresCache — PostgreSQL-backed distributed backend.