wulf-pulse/lib/services/cache.ts
2025-10-28 11:21:04 -04:00

63 lines
1.2 KiB
TypeScript

// Simple in-memory cache with TTL
interface CacheEntry<T> {
data: T;
timestamp: number;
ttl: number;
}
class SimpleCache {
private cache: Map<string, CacheEntry<any>> = new Map();
set<T>(key: string, data: T, ttlMinutes: number = 5): void {
this.cache.set(key, {
data,
timestamp: Date.now(),
ttl: ttlMinutes * 60 * 1000, // Convert to milliseconds
});
}
get<T>(key: string): T | null {
const entry = this.cache.get(key);
if (!entry) {
return null;
}
// Check if expired
if (Date.now() - entry.timestamp > entry.ttl) {
this.cache.delete(key);
return null;
}
return entry.data as T;
}
delete(key: string): void {
this.cache.delete(key);
}
clear(): void {
this.cache.clear();
}
// Clean up expired entries
cleanup(): void {
const now = Date.now();
for (const [key, entry] of this.cache.entries()) {
if (now - entry.timestamp > entry.ttl) {
this.cache.delete(key);
}
}
}
}
// Global cache instance
export const apiCache = new SimpleCache();
// Run cleanup every 5 minutes
if (typeof window === 'undefined') {
// Server-side only
setInterval(() => {
apiCache.cleanup();
}, 5 * 60 * 1000);
}