diff --git a/src/utils/cache.ts b/src/utils/cache.ts new file mode 100644 index 0000000..7cda18c --- /dev/null +++ b/src/utils/cache.ts @@ -0,0 +1,44 @@ +/** + * Simple in-memory TTL cache. + */ +export class Cache { + private store = new Map(); + + constructor(private ttlMs: number) {} + + get(key: string): T | undefined { + const entry = this.store.get(key); + if (!entry) return undefined; + if (Date.now() > entry.expiresAt) { + this.store.delete(key); + return undefined; + } + return entry.value; + } + + set(key: string, value: T): void { + this.store.set(key, { value, expiresAt: Date.now() + this.ttlMs }); + } + + /** + * Get a value from cache, or compute and store it if missing/expired. + * If the compute function throws, the error propagates to the caller + * and nothing is cached. + */ + async getOrSet(key: string, fn: () => Promise): Promise { + const cached = this.get(key); + if (cached !== undefined) return cached; + + const value = await fn(); + this.set(key, value); + return value; + } + + get size(): number { + return this.store.size; + } + + clear(): void { + this.store.clear(); + } +}