clean-jsdoc-theme TypeDoc APIv0.0.0

Cache

Source: Cache.ts:145

Generic cache implementation

Remarks

A feature-rich caching solution with:

  • Configurable TTL (Time To Live)
  • Multiple eviction policies (LRU, LFU, FIFO)
  • Automatic cleanup of expired entries
  • Cache statistics and monitoring
  • Namespace support for logical grouping

Type Parameters

  • K = string — Key type
  • V = unknown — Value type

Example

CODE
Basic usage:
```typescript
const cache = new Cache<string, User>(\{
  maxSize: 100,
  defaultTtl: 5 * 60 * 1000 // 5 minutes
\})

// Set a value
cache.set('user:123', \{ id: '123', name: 'John' \})

// Get a value
const user = cache.get('user:123')

// Check if exists
if (cache.has('user:123')) \{
  // ...
\}
```
CODE
With custom TTL:
```typescript
// Cache for 1 hour
cache.set('session:abc', sessionData, \{ ttl: 60 * 60 * 1000 \})

// No expiry
cache.set('config', configData, \{ ttl: 0 \})
```
CODE
Using getOrSet pattern:
```typescript
const user = await cache.getOrSet('user:123', async () => \{
  return await fetchUserFromDatabase('123')
\})
```

Constructors

new Cache< K = string, V = unknown, >( options: CacheOptions, ): Cache<K, V>

Parameters

  • options (CacheOptions, default: "{}") — Cache configuration options

Returns

Cache<K, V>


Accessors

get size(): number

Gets the current size of the cache

Methods

clear(): this

Clears all entries from the cache

Returns

  • this — This cache instance for chaining

delete(key: K): boolean

Deletes a value from the cache

Parameters

  • key (K) — Cache key

Returns

  • boolean — True if the key was deleted

destroy(): void

Destroys the cache and cleans up resources

Returns

  • void

entries(): [K, V][]

Gets all entries as key-value pairs

Returns

  • [K, V][] — Array of [key, value] tuples

forEach( callback: (value: V, key: K, entry: CacheEntry<V>) => void, ): void

Iterates over cache entries

Parameters

  • callback ((value: V, key: K, entry: CacheEntry<V>) => void) — Function called for each entry

Returns

  • void

Example

CODE
cache.forEach((value, key, entry) => {
  console.log(`${key}: ${value} (hits: ${entry.hits})`)
})

get(key: K): V | undefined

Gets a value from the cache

Parameters

  • key (K) — Cache key

Returns

  • V | undefined — Cached value or undefined if not found/expired

Example

CODE
const value = cache.get('myKey')
if (value !== undefined) {
  console.log('Found:', value)
}

getOrSet< T, >( key: K, factory: () => T | Promise<T>, options?: { ttl?: number }, ): Promise<T>

Gets a value, setting it if not present

Type Parameters

  • T — Value type (extends V)

Parameters

  • key (K) — Cache key
  • factory (() => T | Promise<T>) — Function to create value if not cached
  • options ({ ttl?: number }, optional) — Optional cache settings

Properties

  • ttl (number, optional)

Returns

  • Promise<T> — The cached or newly created value

Example

CODE
const user = await cache.getOrSet(
  'user:123',
  async () => await db.users.find('123'),
  { ttl: 300000 }
)

getStats(): CacheStats

Gets cache statistics

Returns

Example

CODE
const stats = cache.getStats()
console.log(`Hit rate: ${(stats.hitRate * 100).toFixed(2)}%`)
console.log(`Memory: ${stats.memoryUsage} bytes`)

has(key: K): boolean

Checks if a key exists and is not expired

Parameters

  • key (K) — Cache key

Returns

  • boolean — True if key exists and is valid

keys(): K[]

Gets all keys in the cache

Returns

  • K[] — Array of keys

set(key: K, value: V, options?: { ttl?: number }): this

Sets a value in the cache

Parameters

  • key (K) — Cache key
  • value (V) — Value to cache
  • options ({ ttl?: number }, optional) — Optional settings for this entry

Properties

  • ttl (number, optional)

Returns

  • this — This cache instance for chaining

Example

CODE
cache
  .set('key1', 'value1')
  .set('key2', 'value2', { ttl: 60000 })

touch(key: K, ttl?: number): boolean

Updates the TTL for an existing entry

Parameters

  • key (K) — Cache key
  • ttl (number, optional) — New TTL in milliseconds

Returns

  • boolean — True if entry was updated

values(): V[]

Gets all values in the cache

Returns

  • V[] — Array of values