Created
March 25, 2024 03:32
-
-
Save ededejr/bc4c280ebbeaa2cbba5ed3222c7dbb32 to your computer and use it in GitHub Desktop.
an extensible class which provides caching methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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