Przejdź do głównej zawartości

Cache TTL

TtlCache to prosty cache in-memory z automatycznym wygasaniem wpisow po skonfigurowanym czasie (TTL — Time To Live).

import { TtlCache } from '@ksefnik/core'
const cache = new TtlCache(5 * 60 * 1000) // 5 minut TTL
class TtlCache {
constructor(ttlMs?: number) // domyslnie 5 minut
get<T>(key: string): T | undefined // pobierz wartosc (undefined jesli wygasla)
set<T>(key: string, value: T): void // zapisz wartosc z TTL
invalidate(key: string): void // usun konkretny wpis
invalidateAll(): void // usun wszystkie wpisy
get size(): number // liczba wpisow w cache
}

Wpisy wygasaja automatycznie — nie ma potrzeby recznego czyszczenia. Przy kazdym get() sprawdzany jest czas wygasniecia:

get<T>(key: string): T | undefined {
const entry = this.store.get(key)
if (!entry) return undefined
if (Date.now() > entry.expiresAt) {
this.store.delete(key) // usun wygasly wpis
return undefined
}
return entry.value as T
}

Deterministyczna serializacja parametrow zapytania do klucza cache:

import { cacheKey } from '@ksefnik/core'
const key = cacheKey({ from: '2026-03-01', to: '2026-03-31', nip: '5213456784' })
// '{"from":"2026-03-01","nip":"5213456784","to":"2026-03-31"}'

Klucze obiektu sa sortowane alfabetycznie, wiec kolejnosc przekazania parametrow nie ma znaczenia:

cacheKey({ to: '2026-03-31', from: '2026-03-01' })
// '{"from":"2026-03-01","to":"2026-03-31"}' -- identyczny wynik
const cache = new TtlCache(5 * 60 * 1000) // 5 min
async function fetchInvoicesWithCache(
adapter: KsefAdapter,
opts: FetchInvoicesOpts,
): Promise<Invoice[]> {
const key = cacheKey(opts)
// Sprawdz cache
const cached = cache.get<Invoice[]>(key)
if (cached) return cached
// Pobierz z API
const invoices = await adapter.fetchInvoices(opts)
// Zapisz w cache
cache.set(key, invoices)
return invoices
}
async function sendAndInvalidate(adapter: KsefAdapter, input: SendInvoiceInput) {
const result = await adapter.sendInvoice(input)
// Cache moze zawierac nieaktualna liste faktur
cache.invalidateAll()
return result
}
ScenariuszSugerowany TTLPowod
Developerzy testujacy30 sCzeste zmiany, szybki feedback
Skrypt batch10 minDane sie nie zmieniaja podczas przetwarzania
Serwer MCP5 min (domyslne)Balans miedzy swiezoscia a wydajnoscia
CI/CD0 (wylaczony)Zawsze swieze dane
// Wylaczenie cache -- TTL 0 ms
const noCache = new TtlCache(0)
// Dlugi cache -- 30 minut
const longCache = new TtlCache(30 * 60 * 1000)