UNPKG

@remcostoeten/fync

Version:

Unified TypeScript library for 9 popular APIs with consistent functional architecture

96 lines (95 loc) 2.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cache = void 0; exports.createCache = createCache; /** * Simple in-memory cache implementation */ class Cache { constructor(config = {}) { this.store = new Map(); this.config = { enabled: config.enabled !== false, ttl: config.ttl || 5 * 60 * 1000, // 5 minutes default maxSize: config.maxSize || 1000 }; } createKey(method, url, params) { const paramString = params ? JSON.stringify(params) : ''; return `${method}:${url}:${paramString}`; } isExpired(entry) { return Date.now() > entry.expiry; } cleanup() { if (this.store.size > this.config.maxSize) { // Remove oldest entries const entriesToRemove = this.store.size - Math.floor(this.config.maxSize * 0.8); const keys = Array.from(this.store.keys()).slice(0, entriesToRemove); keys.forEach(key => this.store.delete(key)); } } get(method, url, params) { if (!this.config.enabled) return null; const key = this.createKey(method, url, params); const entry = this.store.get(key); if (!entry) return null; if (this.isExpired(entry)) { this.store.delete(key); return null; } return entry.value; } set(method, url, value, params, customTTL) { if (!this.config.enabled) return; const key = this.createKey(method, url, params); const ttl = customTTL || this.config.ttl; this.store.set(key, { value, expiry: Date.now() + ttl }); this.cleanup(); } invalidate(pattern) { if (!pattern) { this.store.clear(); return; } const keys = Array.from(this.store.keys()); keys.forEach(key => { if (key.includes(pattern)) { this.store.delete(key); } }); } invalidateByUrl(url) { const keys = Array.from(this.store.keys()); keys.forEach(key => { if (key.includes(url)) { this.store.delete(key); } }); } clear() { this.store.clear(); } size() { return this.store.size; } setEnabled(enabled) { this.config.enabled = enabled; if (!enabled) { this.clear(); } } setTTL(ttl) { this.config.ttl = ttl; } } exports.Cache = Cache; function createCache(config) { return new Cache(config); }