Skip to main content

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​


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

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

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