interface CacheEntry<T> {
data: T;
expiresAt: number;
}
export class CacheManager {
private cache = new Map<string, CacheEntry<any>>();
private defaultTTL: number;
private cleanupInterval: NodeJS.Timeout;
constructor(ttlMs: number = 5 * 60 * 1000) {
this.defaultTTL = ttlMs;
this.cleanupInterval = setInterval(() => this.cleanup(), 60000);
}
get<T>(key: string): T | null {
const entry = this.cache.get(key);
if (!entry) {
return null;
}
if (Date.now() > entry.expiresAt) {
this.cache.delete(key);
return null;
}
return entry.data as T;
}
set<T>(key: string, data: T, ttlMs?: number): void {
const ttl = ttlMs ?? this.defaultTTL;
this.cache.set(key, {
data,
expiresAt: Date.now() + ttl,
});
}
clear(): void {
this.cache.clear();
}
private cleanup(): void {
const now = Date.now();
for (const [key, entry] of this.cache.entries()) {
if (now > entry.expiresAt) {
this.cache.delete(key);
}
}
}
destroy(): void {
clearInterval(this.cleanupInterval);
this.cache.clear();
}
}
export const cacheManager = new CacheManager(5 * 60 * 1000);