n8n-nodes-semble v2.1.0


n8n-nodes-semble / services/CacheService / CacheService

Class: CacheService

Defined in: services/CacheService.ts:59

Thread-safe in-memory cache service with TTL and auto-refresh capabilities

Extended by

Constructors

Constructor

new CacheService(config): CacheService

Defined in: services/CacheService.ts:66

Parameters

config

CacheConfig

Returns

CacheService

Methods

set()

set\<T>(key, value, ttl?): Promise\<void>

Defined in: services/CacheService.ts:108

Store a value in the cache with optional TTL override

Stores data in the cache with automatic expiration handling and capacity management. If the cache is at capacity, least recently used entries are evicted to make space.

Type Parameters

T

T

Parameters

key

string

The cache key to store under

value

T

The value to cache (any serializable type)

ttl?

number

Optional TTL in seconds (uses default if not provided)

Returns

Promise\<void>

Promise that resolves when value is stored

Example

const cache = new CacheService(config);

// Store with default TTL
await cache.set('user:123', { name: 'John', email: 'john@example.com' });

// Store with custom TTL (5 minutes)
await cache.set('temp:session', sessionData, 300);

// Store complex data structures
await cache.set('api:response', { data: [...], metadata: {...} });

Throws

When cache write operation fails

Since

2.0.0


get()

get\<T>(key): Promise\<null | T>

Defined in: services/CacheService.ts:159

Retrieve a value from the cache by key

Automatically updates access metadata and handles expiration. Returns null if the key doesn't exist or has expired.

Type Parameters

T

T

Parameters

key

string

The cache key to retrieve

Returns

Promise\<null | T>

Promise resolving to cached value or null if not found/expired

Example

const cache = new CacheService(config);
const userdata = await cache.get<User>('user:123');
if (userdata) {
  console.log('Found user:', userdata.name);
}

Throws

When cache read operation fails

Since

2.0.0


has()

has(key): Promise\<boolean>

Defined in: services/CacheService.ts:207

Check if a cache key exists and has not expired

Automatically removes expired entries during the check. This is more efficient than get() when you only need existence.

Parameters

key

string

The cache key to check

Returns

Promise\<boolean>

Promise resolving to true if key exists and is valid

Example

const cache = new CacheService(config);
if (await cache.has('user:123')) {
  console.log('User data is cached');
}

Since

2.0.0


delete()

delete(key): Promise\<boolean>

Defined in: services/CacheService.ts:241

Remove a specific cache entry

Deletes the cache entry for the given key if it exists.

Parameters

key

string

The cache key to delete

Returns

Promise\<boolean>

Promise resolving to true if entry was deleted, false if not found

Example

const cache = new CacheService(config);
const wasDeleted = await cache.delete('user:123');
console.log(`Entry ${wasDeleted ? 'was' : 'was not'} deleted`);

Since

2.0.0


clear()

clear(): Promise\<void>

Defined in: services/CacheService.ts:262

Clear all cache entries

Removes all cached data and resets the cache to empty state. This operation cannot be undone.

Returns

Promise\<void>

Promise that resolves when cache is cleared

Example

const cache = new CacheService(config);
await cache.clear();
console.log('Cache cleared');

Since

2.0.0


generateKey()

generateKey(parts, strategy): string

Defined in: services/CacheService.ts:297

Generate a cache key using the specified strategy

Creates cache keys using different strategies for different use cases: - SIMPLE: Basic underscore-separated keys (fast) - HIERARCHICAL: Colon-separated keys (organized) - HASHED: Hash-based keys (fixed length)

Parameters

parts

string[]

Array of key parts to combine

strategy

CacheKeyStrategy = CacheKeyStrategy.HIERARCHICAL

The strategy to use for key generation (default: HIERARCHICAL)

Returns

string

Generated cache key string

Example

const cache = new CacheService(config);

// Hierarchical key
const key1 = cache.generateKey(['user', '123', 'profile'], CacheKeyStrategy.HIERARCHICAL);
// Result: "user:123:profile"

// Hashed key
const key2 = cache.generateKey(['very', 'long', 'key', 'parts'], CacheKeyStrategy.HASHED);
// Result: "hash_123456789"

Throws

When invalid strategy is provided

Since

2.0.0


refreshEntry()

refreshEntry\<T>(key, refreshFunction, ttl?): Promise\<T>

Defined in: services/CacheService.ts:391

Refresh a specific cache entry with new data

Updates cache entry by calling the provided refresh function. Prevents concurrent refreshes of the same key and handles errors gracefully.

Type Parameters

T

T

Parameters

key

string

The cache key to refresh

refreshFunction

() => Promise\<T>

Async function that returns fresh data

ttl?

number

Optional TTL in seconds (uses default if not provided)

Returns

Promise\<T>

Promise resolving to the refreshed data

Example

const cache = new CacheService(config);

const freshUserData = await cache.refreshEntry(
  'user:123',
  async () => {
    const response = await api.getUser(123);
    return response.data;
  },
  300 // 5 minute TTL
);

Throws

When refresh operation fails

Since

2.0.0


refreshAll()

refreshAll(refreshFunctions): Promise\<CacheRefreshResult>

Defined in: services/CacheService.ts:443

Force refresh all cache entries

Parameters

refreshFunctions

Map\<string, () => Promise\<any>>

Returns

Promise\<CacheRefreshResult>


refreshExpired()

refreshExpired(refreshFunctions): Promise\<CacheRefreshResult>

Defined in: services/CacheService.ts:468

Refresh expired entries only

Parameters

refreshFunctions

Map\<string, () => Promise\<any>>

Returns

Promise\<CacheRefreshResult>


startAutoRefresh()

private startAutoRefresh(): void

Defined in: services/CacheService.ts:506

Start automatic background refresh

Returns

void


stopAutoRefresh()

stopAutoRefresh(): void

Defined in: services/CacheService.ts:530

Stop automatic background refresh

Returns

void


cleanupExpired()

private cleanupExpired(): Promise\<number>

Defined in: services/CacheService.ts:540

Clean up expired entries

Returns

Promise\<number>


getStats()

getStats(): object

Defined in: services/CacheService.ts:561

Get cache statistics

Returns

object

size

size: number

maxSize

maxSize: number

hitRate

hitRate: number

expiredEntries

expiredEntries: number

refreshingEntries

refreshingEntries: number


evictLeastRecentlyUsed()

private evictLeastRecentlyUsed(): void

Defined in: services/CacheService.ts:599

Evict least recently used entry

Returns

void


shutdown()

shutdown(): Promise\<void>

Defined in: services/CacheService.ts:620

Shutdown the cache service

Returns

Promise\<void>

Properties

cache

private readonly cache: Map\<string, CacheEntry\<any>>

Defined in: services/CacheService.ts:60


config

private readonly config: CacheConfig

Defined in: services/CacheService.ts:61


refreshLocks

private readonly refreshLocks: Set\<string>

Defined in: services/CacheService.ts:62


autoRefreshTimer?

private optional autoRefreshTimer: Timeout

Defined in: services/CacheService.ts:63


isShuttingDown

private isShuttingDown: boolean = false

Defined in: services/CacheService.ts:64