@johngw/stream
Version:
Reactive programming tools using the WHATWG Streams API.
63 lines (62 loc) • 1.59 kB
TypeScript
/**
* Timed cache using a `Storage` interface.
*
* @group Storages
* @example
* Letting cache expire.
*
* ```
* const cache = new StorageCache(localStorage, 'my-cache', 30 * 60_000)
*
* cache.set(['a', 'path'], 'foo')
* cache.get(['a', 'path'])
* // 'foo'
*
* await setTimeout(30 * 60_000)
* cache.get(['a', 'path'])
* // undefined
* ```
* @example
* Manually invalidating cache.
*
* ```
* const cache = new StorageCache(localStorage, 'my-cache', 30 * 60_000)
* cache.set(['foo', 'bar'], 'a')
* cache.set(['foo', 'rab'], 'b')
*
* // Remove a specific cache item
* cache.unset(['foo', 'bar'])
*
* // Remove all "foos"
* cache.unset(['foo'])
* ```
*/
export declare class StorageCache {
#private;
constructor(storage: Storage, key: string, ms: number);
get ms(): number;
/**
* Ads or overrides an item in the cache.
*/
set(path: string[], value: unknown, ms?: number): void;
/**
* Removes one or more items from the cache using the path
* as key hierarchy.
*/
unset(path: string[]): void;
/**
* Returns the cached value. Returns undefined if it doesn't
* exist or if the cache is stale.
*/
get(path: string[]): unknown;
/**
* Checks if a path has cache. If not, updates it and returns `true`.
* Otherwise returns `false`.
*/
updateIfStale(path: string[], update: () => unknown | Promise<unknown>, ms?: number): Promise<boolean>;
/**
* Returns the remaining cache time for an item.
*/
timeLeft(path: string[]): number;
getAll(): any;
}