@streetjs/cache
v1.0.0
Published
StreetJS in-memory cache foundation: a bounded LRU cache with per-entry TTL, periodic sweep of expired entries, and O(1) get/set/delete. Zero runtime dependencies.
Maintainers
Readme
@streetjs/cache
The in-memory cache foundation for StreetJS: a bounded LRU cache with per-entry TTL, O(1) operations, and a periodic sweep of expired entries.
Zero runtime dependencies. Built on Node.js core only, matching the StreetJS minimal, carefully curated dependency footprint. Generic and reusable by any application.
npm install @streetjs/cacheThis is the standalone home of the LRU cache that also backs
streetjs/cache; thestreetjsframework re-exports it, so there is a single implementation.
Quick start
import { LruCache } from '@streetjs/cache';
const cache = new LruCache<string, User>({ maxEntries: 1000, ttlMs: 60_000 });
cache.set('u:7', user);
cache.get('u:7'); // User | undefined (refreshes recency)
cache.has('u:7'); // boolean (purges if expired)
cache.delete('u:7');
cache.size; // number of stored entries
cache.clear();
cache.destroy(); // stop the background sweep on shutdownBehavior
- Bounded — once
maxEntriesis exceeded, the least-recently-used entry is evicted.getandset(on an existing key) refresh recency. - TTL — each entry expires
ttlMsafter its last write. Expiry is applied lazily onget/hasand proactively by a background sweep. - O(1) — a
Mapplus an intrusive doubly-linked list give constant-timeget/set/delete/has. - Keys — any key is coerced to a string, so
1and'1'address the same entry.
Options
new LruCache({
maxEntries: 1000, // required, >= 1
ttlMs: 60_000, // required
autoSweep: true, // default true; the sweep timer is unref'd (won't hold the process open)
clock: () => Date.now(), // injectable time source for deterministic tests
});Set autoSweep: false (and rely on lazy expiry) for short-lived caches or tests; pass a
custom clock to advance time deterministically.
Dependency injection
Depends on no container. Exports a CACHE token (a global Symbol) for interface-first
wiring:
import { CACHE, LruCache } from '@streetjs/cache';
container.register(CACHE, new LruCache({ maxEntries: 500, ttlMs: 30_000 }));Public API
LruCache · LruOptions · CACHE token.
See ARCHITECTURE.md for design notes, and
src/examples/integration.ts for a runnable read-through-cache example.
License
MIT © street contributors
