cacheable.ts
an extensible class which provides caching methods
import TTLCache, { Options } from '@isaacs/ttlcache';
export type CacheOptions<K = string, V = unknown> = Options<K, V>;
export class Cacheable<K = string, V = unknown> {
protected cache: TTLCache<K, V>;
constructor(options: Options<K, V> = { ttl: 1000 * 60 * 10 }) {
this.cache = new TTLCache(options);
}
protected async memoize<T extends V>(
key: K,
fn: () => Promise<T>,
options?: CacheOptions<K, V>,
): Promise<T> {
if (!this.cache.has(key)) {
this.cache.set(key, await fn(), options);
}
return this.cache.get(key) as T;
}
public clearCache() {
this.cache.clear();
}
}