UNPKG

@croct/cache

Version:

An abstraction layer for caching.

55 lines (54 loc) 2.1 kB
import { Clock } from '@croct/time'; import { CacheLoader, CacheProvider } from './cacheProvider'; import { TimestampedCacheEntry } from './timestampedCacheEntry'; type Configuration<K, V> = { /** * The underlying cache provider to use for storing the cached data. */ cacheProvider: CacheProvider<K, TimestampedCacheEntry<V>>; /** * The freshness period of the cached data in seconds. * * It defines the time duration for which the cache entry * is considered fresh. Once the freshness period expires, * the data will be revalidated in the background while * still serving the stale value on subsequent gets. * * For example, if freshPeriod is set to 60 seconds, * the cache entry will be considered fresh for 60 seconds * after its creation or update. After 60 seconds, it will be * evaluated in the background on subsequent gets, but the stale value * will still be served until the revalidation is complete. */ freshPeriod: number; /** * The clock to use for time-related operations. * * It is used for retrieving the current time and for time calculations. * If not provided, the default clock is used. * * @default DefaultClockProvider.getClock() */ clock?: Clock; /** * The handler for background revalidation errors. * * It is a function that is called when an error occurs during * background revalidation of a cache entry. If not provided, * errors during background revalidation are ignored. * * The most common use case for this handler is logging. */ errorHandler?: (error: Error) => void; }; export declare class StaleWhileRevalidateCache<K, V> implements CacheProvider<K, V> { private readonly cacheProvider; private readonly freshPeriod; private readonly clock; private readonly errorHandler; constructor(config: Configuration<K, V>); get(key: K, loader: CacheLoader<K, V>): Promise<V>; set(key: K, value: V): Promise<void>; delete(key: K): Promise<void>; } export {};