Skip to main content

@rtorcato/js-common / cache

cache

Interfaces​

TtlCacheOptions​

Defined in: cache/index.ts:1

Properties​

ttlMs​

ttlMs: number

Defined in: cache/index.ts:6

How long a loaded value counts as fresh, in milliseconds. 0 never caches (every get calls load); Infinity never expires. Throws RangeError if NaN or negative.

staleOnError?​

optional staleOnError?: boolean

Defined in: cache/index.ts:8

When a refresh throws, serve the last good value instead of rethrowing. Default false.


TtlCache​

Defined in: cache/index.ts:11

Type Parameters​

V​

V

Methods​

get()​

get(key, load): Promise<V>

Defined in: cache/index.ts:13

Returns the fresh cached value for key, or calls load and caches the result.

Parameters​
key​

string

load​

() => Promise<V>

Returns​

Promise<V>

delete()​

delete(key): void

Defined in: cache/index.ts:15

Drops one key, so the next get loads again.

Parameters​
key​

string

Returns​

void

clear()​

clear(): void

Defined in: cache/index.ts:17

Drops every key.

Returns​

void

Functions​

createTtlCache()​

createTtlCache<V>(options): TtlCache<V>

Defined in: cache/index.ts:39

In-memory TTL cache with optional stale-on-error.

get serves a value younger than ttlMs without calling load. Concurrent gets for the same key share one load. With staleOnError, a failed refresh returns the last good value (however old) and leaves it in place, so the next get retries; with no good value yet, or without staleOnError, the error is rethrown. Entries are never evicted by age, only replaced — bound the key space yourself or call delete / clear.

Example​

const quotes = createTtlCache<Quote>({ ttlMs: 60_000, staleOnError: true })
const quote = await quotes.get('AAPL', () => fetchQuote('AAPL'))

Type Parameters​

V​

V

Parameters​

options​

TtlCacheOptions

Freshness window and error behaviour.

Returns​

TtlCache<V>

Throws​

If ttlMs is NaN or negative.