Skip to main content
current (v2.x.x)

Cache

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


Interfaces & Types

interface TTLCacheOptions {
/** Default time-to-live in milliseconds for cache entries */
ttlMs?: number;
/** Maximum number of entries to keep in cache (uses LRU eviction policy) */
maxSize?: number;
/** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */
autoCleanupMs?: number;
}

Function Documentation & Usage Examples

import { TTLCache } from '@catbee/utils/cache';

const cache = new TTLCache<string, number>({ ttlMs: 60000, maxSize: 1000, autoCleanupMs: 30000 });

set()

Add or update a cache entry with the default TTL.

Method Signature:

set(key: K, value: V): void

Parameters:

  • key: The cache key.
  • value: The cache value.

Examples:

cache.set('foo', 42);

setWithTTL()

Add or update a cache entry with a custom TTL.

Method Signature:

setWithTTL(key: K, value: V, ttlMs: number): void

Parameters:

  • key: The cache key.
  • value: The cache value.
  • ttlMs: Time-to-live in milliseconds.

Examples:

cache.setWithTTL('bar', 99, 5000); // 5 second 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, otherwise false.

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, otherwise false.

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 and return the count of removed entries.

Method Signature:

cleanup(): number

Returns:

  • The number of entries removed.

Examples:

const removed = cache.cleanup();
console.log(`Removed ${removed} expired entries`);

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, otherwise false.

Examples:

cache.refresh('session', 600_000);

stats()

Get cache statistics.

Method Signature:

stats(): { size: number; validEntries: number; expiredEntries: number; maxSize?: number }

Returns:

  • An object containing:
    • size: Total number of entries in cache (including expired)
    • validEntries: Number of valid (non-expired) entries
    • expiredEntries: Number of expired entries
    • maxSize: Maximum size limit (if configured)

Examples:

const stats = cache.stats();
console.log(`Cache: ${stats.validEntries}/${stats.size} valid, max: ${stats.maxSize}`);

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);