Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Simple in-memory TTL cache.
*/
export class Cache<T> {
private store = new Map<string, { value: T; expiresAt: number }>();

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<T>): Promise<T> {
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();
}
}