UNPKG

neura-sdk

Version:

TypeScript SDK for interacting with the Neura AI API

53 lines (52 loc) 1.47 kB
const DEFAULT_TTL = 5 * 60 * 1000; // 5 minutes in milliseconds export class MemoryCache { constructor(defaultTTL = DEFAULT_TTL) { this.cache = new Map(); this.defaultTTL = defaultTTL; // Periodically clean expired entries setInterval(() => this.cleanExpired(), 60 * 1000); // Clean every minute } get(key) { const entry = this.cache.get(key); if (!entry) { return undefined; } // Check if the entry has expired if (entry.expires < Date.now()) { this.cache.delete(key); return undefined; } return entry.value; } set(key, value, options) { const ttl = options?.ttl ?? this.defaultTTL; const expires = Date.now() + ttl; this.cache.set(key, { value, expires }); } has(key) { const entry = this.cache.get(key); if (!entry) { return false; } // Check if the entry has expired if (entry.expires < Date.now()) { this.cache.delete(key); return false; } return true; } delete(key) { return this.cache.delete(key); } clear() { this.cache.clear(); } cleanExpired() { const now = Date.now(); for (const [key, entry] of this.cache.entries()) { if (entry.expires < now) { this.cache.delete(key); } } } }