Skip to content

Instantly share code, notes, and snippets.

@ededejr
Created March 25, 2024 03:32
Show Gist options
  • Save ededejr/bc4c280ebbeaa2cbba5ed3222c7dbb32 to your computer and use it in GitHub Desktop.
Save ededejr/bc4c280ebbeaa2cbba5ed3222c7dbb32 to your computer and use it in GitHub Desktop.
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment