import { LRUCache } from 'lru-cache'; import { CacheAdapter } from './types.js'; export class MemoryCache implements CacheAdapter { private cache: LRUCache; constructor() { const defaultTtl = process.env.CACHE_DEFAULT_TTL ? parseInt(process.env.CACHE_DEFAULT_TTL) : 1000 * 60 * 5; // 5 mins default this.cache = new LRUCache({ max: 500, ttl: defaultTtl, updateAgeOnGet: false, }); } async get(key: string): Promise { const value = this.cache.get(key); return (value as T) || null; } async set(key: string, value: T, ttl?: number): Promise { this.cache.set(key, value, { ttl: ttl ? ttl * 1000 : undefined }); } async del(key: string): Promise { this.cache.delete(key); } async flush(pattern?: string): Promise { if (pattern) { // Manual iteration for pattern matching (simple startsWith) // LRUCache doesn't support regex keys easily without walking for (const key of this.cache.keys()) { if (typeof key === 'string' && key.startsWith(pattern)) { this.cache.delete(key); } } } else { this.cache.clear(); } } }