@cache-utils/cache-utils
v0.0.3
Published
Cache anything in one line — CacheManager, MemoryAdapter, RedisAdapter, and @Cacheable/@CacheEvict decorators in one install.
Maintainers
Readme
@cache-utils/cache-utils
Cache anything in one line. Swap Redis in later without touching the code that calls it.
npm install @cache-utils/cache-utilsimport { CacheManager } from "@cache-utils/cache-utils";
const cache = new CacheManager(); // in-memory, zero config
const product = await cache.wrap(
`product:${id}`,
() => db.products.findById(id),
{
ttlSeconds: 60,
},
);That's the whole setup. wrap checks the cache, calls your function on a
miss, caches the result, and returns it either way. No adapter to configure,
no client to instantiate, nothing to await before your first call.
Why cache-utils
- One interface, any backend.
@cache-utils/coredefines a 4-methodCacheAdapterinterface. Swap the defaultMemoryAdapterforRedisAdapter— or write your own in an afternoon — and nothing else in your code changes. - Not just
get/set. Distributed locks (withLock), key namespacing, and@Cacheable/@CacheEvictdecorators are built in, not bolted on. - One install covers it. The
@cache-utils/cache-utilspackage bundles core, every built-in adapter, and the decorators — see Packages if you'd rather install a smaller, scoped piece.
See it running
Runnable examples in examples/ — npm install at the repo
root, then bun run dev (or npm run dev) in any of them:
examples/express— Express + the default in-memory adapter, with a live hit/miss demo pageexamples/custom-adapter-express— same demo, backed by a hand-written JSON-fileCacheAdapterexamples/nestjs—@Cacheable/@CacheEvicton a Nest controllerexamples/react— cache-utils running entirely in the browser, no backend
Docs
Packages
packages/cache-utils—@cache-utils/cache-utils: the convenience bundle. Re-exportsCacheManager/MemoryAdapterfrom core,RedisAdapterfrom adapter-redis, andCacheable/CacheEvict/configureCacheManagerfrom decorators, so every built-in adapter and the decorator sugar are available from one install, no hunting for the right scoped package. (@cache-utils/nestjsis the one integration left out — it pulls in@nestjs/commonas a peer dependency, which shouldn't be forced on non-Nest consumers.)packages/core—@cache-utils/core: theCacheAdapterinterface,CacheManagerclass, and the defaultMemoryAdapter. No runtime dependencies.packages/adapter-memory—@cache-utils/adapter-memory: re-exportsMemoryAdapterfrom@cache-utils/corefor anyone who prefers importing it explicitly by adapter package name.packages/adapter-redis—@cache-utils/adapter-redis: wrapsioredis.packages/decorators—@cache-utils/decorators:@Cacheable/@CacheEvictmethod decorators for any TypeScript project usingexperimentalDecorators, regardless of DI framework (or none at all).packages/nestjs—@cache-utils/nestjs: aCacheUtilsModule.forRoot()dynamic module wiring aCacheManagerinto Nest's DI and into@cache-utils/decorators, so@Cacheable/@CacheEvictwork on Nest-managed classes with no extra setup.
@cache-utils/cache-utils is the easiest way to get started — one install,
every adapter ready to import. The scoped @cache-utils/* packages remain
available individually for anyone who wants a leaner install (e.g.
@cache-utils/core alone has zero dependencies; pulling in
@cache-utils/cache-utils pulls in ioredis via adapter-redis even if you
only ever use the in-memory default).
The cross-language contract (what a Go/Python port would need to implement) lives in the sibling ../cache-utils-spec/SPEC.md.
CacheAdapter
The interface any backend implements:
interface CacheAdapter {
get(key: string): Promise<string | null>;
set(key: string, value: string, ttlSeconds?: number): Promise<void>;
setIfNotExists(
key: string,
value: string,
ttlSeconds: number,
): Promise<boolean>;
del(key: string | string[]): Promise<void>;
mget?(keys: string[]): Promise<(string | null)[]>;
mset?(entries: Array<[string, string]>, ttlSeconds?: number): Promise<void>;
scanByPrefix?(prefix: string): Promise<string[]>;
}Only get/set/setIfNotExists/del are required. mget/mset/scanByPrefix
are optional extras an adapter can implement for efficiency.
CacheManager
class CacheManager {
wrap<T>(
key: string,
callback: () => Promise<T>,
options?: WrapOptions,
): Promise<T>;
get<T>(key: string): Promise<T | null>;
set<T>(key: string, value: T, ttlSeconds?: number): Promise<void>;
del(key: string | string[]): Promise<void>;
acquireLock(key: string, ttlSeconds: number): Promise<Lock | null>;
releaseLock(lock: Lock): Promise<void>;
withLock<T>(
key: string,
ttlSeconds: number,
fn: () => Promise<T>,
): Promise<T | null>;
namespace(prefix: string): CacheManager;
}
interface WrapOptions {
ttlSeconds?: number;
onError?: "fallthrough" | "throw"; // default "fallthrough"
}CacheManager's adapter argument is optional and defaults to an in-memory
MemoryAdapter — that's what new CacheManager() in the example above is
using.
Usage — Redis
import { CacheManager, RedisAdapter } from "@cache-utils/cache-utils";
import Redis from "ioredis";
// freely use your existing client / connection
const redisClient = new Redis(process.env.REDIS_URL!);
const cache = new CacheManager(new RedisAdapter(redisClient));
// distributed lock, e.g. guarding a payout job from running twice
const result = await cache.withLock("payout-job", 30, async () => {
return runPayoutJob();
});Namespacing
const productCache = cache.namespace("product:");
const userCache = cache.namespace("user:");
// same backend, keys never collide@Cacheable / @CacheEvict (plain TypeScript, any DI or none)
Requires experimentalDecorators in your project's tsconfig.json (the same
assumption Nest itself makes — no other setup needed).
import {
CacheManager,
Cacheable,
CacheEvict,
configureCacheManager,
} from "@cache-utils/cache-utils";
configureCacheManager(new CacheManager());
class ProductService {
@Cacheable({ ttlSeconds: 86400, keyFrom: (id: string) => `product:${id}` })
async getProduct(id: string) {
return db.products.findById(id);
}
@CacheEvict({ keyFrom: (id: string) => `product:${id}` })
async updateProduct(id: string, data: unknown) {
return db.products.update(id, data);
}
}configureCacheManager is a single module-level setter — call it once at
startup with whichever CacheManager your app uses. It doesn't assume any
particular DI container.
ttlSeconds is fixed at decoration time. If the TTL needs to vary per call
(e.g. from a request parameter), use ttlSecondsFrom instead — it receives
the same arguments the method was called with, same as keyFrom:
@Cacheable({
keyFrom: (id: string) => `product:${id}`,
ttlSecondsFrom: (_id: string, ttlMs: number) => Math.ceil(ttlMs / 1000),
})
async getProduct(id: string, ttlMs: number) { ... }NestJS
import { Module } from "@nestjs/common";
import { CacheUtilsModule } from "@cache-utils/nestjs";
import { RedisAdapter } from "@cache-utils/adapter-redis";
import Redis from "ioredis";
@Module({
imports: [
CacheUtilsModule.forRoot({
adapter: new RedisAdapter(new Redis(process.env.REDIS_URL!)),
isGlobal: true,
}),
],
})
export class AppModule {}@Cacheable/@CacheEvict (re-exported from @cache-utils/decorators) then
work on any Nest-managed provider — the module wires them to the same
CacheManager it registers under the CACHE_MANAGER injection token for
manual get/set/wrap/lock use.
Scope of this pass (Phase 0)
wrap is a plain read-through cache: get → on miss call the callback → cache
the result. It does not yet include single-flight in-process deduplication,
distributed leases, tag-based invalidation, or stale-while-revalidate — those
are later phases in cache-utils-plan (1).md. adapter-memory is an
unbounded Map with lazy TTL expiry; it does not yet implement W-TinyLFU
eviction. See the plan doc's roadmap (sections 6, 8, 11) for what's coming.
@cache-utils/decorators and @cache-utils/nestjs are TypeScript/DI
convenience layers only — they are explicitly out of scope for the
cross-language spec (see SPEC.md §6), so a Go or Python port has no
obligation to replicate them.
Contributing
Setup
npm install
npm run build # tsc per package → dist/ — required once; each package's
# main/types point at dist so cross-package imports (and
# a real `npm pack`) resolve the same way a real install would
docker compose up -d # starts redis:7-alpine on localhost:6382 for adapter-redis tests
bun test # runs every *.test.ts across all packages
npm run typecheck # tsc --noEmit per packageRe-run npm run build after editing any package's src/ — bun test and
npm run typecheck read source directly and don't need it, but anything that
resolves a package by name across a workspace boundary (e.g.
@cache-utils/adapter-memory importing @cache-utils/core) does, since
main/types point at dist/.
The Redis test suite auto-skips (with a console warning) if it can't reach
REDIS_URL (defaults to redis://localhost:6382), so bun test still works
without Docker — you just won't get adapter-redis coverage.
The root tsconfig.json (not just tsconfig.base.json) sets
experimentalDecorators/emitDecoratorMetadata directly, with no extends.
Bun resolves the tsconfig for bun test relative to the process's working
directory, and its transpiler doesn't currently merge experimentalDecorators
through an extends chain — so this file has to be self-contained for the
decorators/nestjs packages' tests to transpile decorator syntax at all.
Each package's own tsconfig.json still extends tsconfig.base.json for
npm run typecheck (tsc doesn't have this bug).
Project layout
packages/* is the published library (one npm workspace per package,
@cache-utils/* scoped except the cache-utils bundle itself).
examples/* are runnable demo apps (private: true, never published) —
good places to see a change in context before you land it.
Adding a new adapter
Implement CacheAdapter (packages/core/src/types.ts) — only
get/set/setIfNotExists/del are required, mget/mset/scanByPrefix
are optional. Check your implementation against
cache-utils-spec/SPEC.md before opening a
PR — it's the contract every adapter (and every language port) has to match:
null semantics for missing vs. expired keys, TTL always in whole seconds,
the exact lock-key prefix, and so on. Mirror the test suite shape in
packages/adapter-memory/test or packages/adapter-redis/test for your new
adapter.
