cache
Provider-agnostic JSON caching with in-memory and Redis adapters.
API
createCacheStore(config:CacheStoreConfig): the store contract the services use.createMemoryCacheProvider,createRedisCacheProvider: storage providers.createCacheMiddleware: oRPC middleware;assertValidCacheTtl: validates a TTL.
Layers
CacheProviderstores strings, applies millisecond TTLs, enumerates key prefixes, and clears its own storage scope.CacheStorevalidates keys, serializes JSON values, implements cache-aside loading, tracks hit/miss statistics, and maintains invalidation tags.createMemoryCacheProviderstores process-local entries with lazy TTL cleanup.createRedisCacheProvidernamespaces keys and usesSCANplus batchedUNLINK; it never owns the Redis connection lifecycle.
Usage
import { createCacheStore } from "@gentlemans-stack/cache/cache-store";
import { createMemoryCacheProvider } from "@gentlemans-stack/cache/memory-cache-provider";
const cache = createCacheStore(createMemoryCacheProvider(), { defaultTtlMs: 60_000 });
const user = await cache.getOrSet("user:42", loadUser, { tags: ["users"] });
await cache.invalidateTag("users");For Redis, compose the connected client supplied by redis-connector.
import { createRedisCacheProvider } from "@gentlemans-stack/cache/redis-cache-provider";
const provider = createRedisCacheProvider(redisConnector.getConnection(), {
namespace: "todo-service",
scanCount: 100,
});
const cache = createCacheStore(provider, { defaultTtlMs: 60_000 });Values must be JSON serializable. undefined is not cacheable; null is a valid cached value. Tag metadata receives the same TTL as its entry, and replacing or deleting an entry removes its previous tag indexes.
oRPC middleware
createCacheMiddleware caches or invalidates a procedure's response based on its own contract
metadata. Attach it once at the root implementer and every procedure behaves according to its
own cache/invalidatesCache fields; a procedure with neither set passes through untouched.
import { createCacheMiddleware } from "@gentlemans-stack/cache/cache.middleware";
type AppContext = { cache: CacheStore /* ...rest of your RequestContext */ };
const cache = createCacheMiddleware<AppContext>();
const publicImplementer = implement(contract).$context<AppContext>().use(cache);Declare the same metadata shape on the contract (oc.$meta<{ cache?: readonly string[]; invalidatesCache?: readonly string[] }>({})),
then per procedure.
const list = base.route({ ... }).meta({ cache: ["todo"] }).output(...);
const create = base.route({ ... }).meta({ invalidatesCache: ["todo"] }).input(...).output(...);A cache key is derived from the procedure's path and input; invalidation only runs after the handler succeeds.
Commands
pnpm nx run cache:typecheck # type-check the package
pnpm nx run cache:test # run the Vitest suite