UNPKG

@metis-w/api-client

Version:

Modern TypeScript HTTP API client with dynamic routes, parameterized endpoints, interceptors, and advanced features

71 lines 2.35 kB
/** * Simple in-memory cache interceptor for GET requests */ export class CacheInterceptor { constructor(options = {}) { this.cache = new Map(); this.requestInterceptor = (config) => { // Only for GET requests if (config.method?.toUpperCase() !== "GET") { return config; } const key = this.options.cacheKey(config); const cached = this.cache.get(key); if (cached && this.isValid(cached.timestamp)) { console.info(`📦 Cache HIT for ${config.url}`); // In a real application, there would be a mechanism to return cached data here } return config; }; this.responseInterceptor = (response, config) => { if (config?.method?.toUpperCase() === "GET" && response.success) { const key = this.options.cacheKey(config); // Clear old entries if we've reached the limit if (this.cache.size >= this.options.maxSize) { this.clearOldest(); } this.cache.set(key, { data: response, timestamp: Date.now(), }); console.info(`💾 Cached response for ${config.url}`); } return response; }; this.options = { ttl: options.ttl || 5 * 60 * 1000, // 5 minutes default maxSize: options.maxSize || 100, cacheKey: options.cacheKey || this.defaultCacheKey, }; } defaultCacheKey(config) { const params = config.params ? JSON.stringify(config.params) : ""; return `${config.method}_${config.url}_${params}`; } isValid(timestamp) { return Date.now() - timestamp < this.options.ttl; } clearOldest() { const oldestKey = this.cache.keys().next().value; if (oldestKey) { this.cache.delete(oldestKey); } } /** * Clear all cached entries */ clear() { this.cache.clear(); } /** * Get cache statistics */ getStats() { return { size: this.cache.size, maxSize: this.options.maxSize, ttl: this.options.ttl, }; } } //# sourceMappingURL=cache.js.map