Cache Utilities
In-memory TTL cache with advanced features for efficient data caching and retrieval. Provides a flexible, type-safe cache class with TTL, LRU eviction, auto-cleanup, and batch operations.
API Summary​
TTLCache<K, V>
- Generic class with key typeK
and value typeV
.set(key: K, value: V, ttlMs?: number): void
- Add or update a cache entry, optionally with a custom TTL.get(key: K): V | undefined
- Retrieve a value from cache.has(key: K): boolean
- Check if key exists in cache.delete(key: K): boolean
- Remove a key from cache.clear(): void
- Remove all entries from cache.size(): number
- Get the number of entries in cache.cleanup(): void
- Remove expired entries.keys(): K[]
- Get all valid keys in the cache.values(): V[]
- Get all valid values in the cache.entries(): Array<[K, V]>
- Get all valid key-value pairs.forEach(callbackFn: (value: V, key: K) => void): void
- Execute function for each entry.setMany(entries: [K, V][]): void
- Set multiple entries at once.getMany(keys: K[]): (V | undefined)[]
- Get multiple values at once.refresh(key: K, ttlMs?: number): boolean
- Extend expiration of a key.stats(): object
- Get cache statistics.destroy(): void
- Stop auto-cleanup interval.getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V>
- Get or compute a value if missing.
Interfaces & Types​
interface TTLCacheOptions {
ttlMs?: number; // Default TTL in milliseconds
maxSize?: number; // Maximum number of entries
autoCleanupMs?: number; // Auto cleanup interval
}
Function Documentation & Usage Examples​
import { TTLCache } from '@catbee/utils';
const cache = new TTLCache<string, number>({ ttlMs: 60000, maxSize: 1000, autoCleanupMs: 30000 });
set()
​
Add or update a cache entry, optionally with a custom TTL.
Method Signature:
set(key: K, value: V, ttlMs?: number): void
Parameters:
key
: The cache key.value
: The cache value.ttlMs
: Optional time-to-live in milliseconds.
Examples:
cache.set("foo", 42);
cache.set("bar", 99, 5000); // custom TTL
get()
​
Retrieve a value from cache or compute it if missing.
Method Signature:
get(key: K): V | undefined
Parameters:
key
: The cache key.
Returns:
- The cached value or
undefined
if not found or expired.
Examples:
const value = cache.get("foo"); // 42
has()
​
Check if key exists in cache.
Method Signature:
has(key: K): boolean
Parameters:
key
: The cache key.
Returns:
true
if the key exists and is valid, otherwisefalse
.
Examples:
if (cache.has("foo")) { /* ... */ }
delete()
​
Remove a key from cache.
Method Signature:
delete(key: K): boolean
Parameters:
key
: The cache key.
Returns:
true
if the key was found and removed, otherwisefalse
.
Examples:
cache.delete("foo");
clear()
​
Remove all entries from cache.
Method Signature:
clear(): void
Examples:
cache.clear();
size()
​
Get the number of entries in cache.
Method Signature:
size(): number
Returns:
- The count of valid entries in the cache.
Examples:
const count = cache.size();
cleanup()
​
Remove expired entries.
Method Signature:
cleanup(): void
Examples:
const removed = cache.cleanup();
keys()
​
Get all valid keys in the cache.
Method Signature:
*keys(): IterableIterator<K>
Returns:
- An iterator over the valid keys in the cache.
Examples:
const keys = Array.from(cache.keys());
values()
​
Get all valid values in the cache.
Method Signature:
*values(): IterableIterator<V>
Returns:
- An iterator over the valid values in the cache.
Examples:
const values = Array.from(cache.values());
entries()
​
Get all valid key-value pairs.
Method Signature:
*entries(): IterableIterator<[K, V]>
Returns:
- An iterator over the valid key-value pairs in the cache.
Examples:
const entries = Array.from(cache.entries());
forEach()
​
Execute function for each entry.
Method Signature:
forEach(callbackFn: (value: V, key: K) => void): void
Parameters:
callbackFn
: Function to execute for each entry.
Examples:
cache.forEach((value, key) => { console.log(key, value); });
setMany()
​
Set multiple entries at once.
Method Signature:
setMany(entries: [K, V][]): void
Parameters:
entries
: Array of key-value pairs to set.
Examples:
cache.setMany([["a", 1], ["b", 2]]);
getMany()
​
Get multiple values at once.
Method Signature:
getMany(keys: K[]): (V | undefined)[]
Parameters:
keys
: Array of cache keys to retrieve.
Returns:
- An array of values or
undefined
for missing/expired keys.
Examples:
const values = cache.getMany(["a", "b", "x"]);
refresh()
​
Extend expiration of a key.
Method Signature:
refresh(key: K, ttlMs?: number): boolean
Parameters:
key
: The cache key.ttlMs
: Optional new time-to-live in milliseconds.
Returns:
true
if the key was found and refreshed, otherwisefalse
.
Examples:
cache.refresh("session", 600_000);
stats()
​
Get cache statistics.
Method Signature:
stats(): object
Returns:
- An object containing cache statistics like hits, misses, size, etc.
Examples:
const stats = cache.stats();
destroy()
​
Stop auto-cleanup interval.
Method Signature:
destroy(): void
Examples:
cache.destroy();
getOrCompute()
​
Get or compute a value if missing.
Method Signature:
getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V>
Parameters:
key
: The cache key.producer
: Function to produce the value if not found.ttlMs
: Optional time-to-live in milliseconds.
Returns:
- The cached or newly computed value.
Examples:
const value = await cache.getOrCompute("user:1", async () => fetchUserFromDb(1), 10_000);