import { HttpInterceptorFn, HttpResponse } from '@angular/common/http'; import { of } from 'rxjs'; import { tap } from 'rxjs/operators'; const cache = new Map, timestamp: number }>(); const CACHE_DURATION = 5 * 60 * 1000; // 5 минут export const cacheInterceptor: HttpInterceptorFn = (req, next) => { // Кэшируем только GET запросы if (req.method !== 'GET') { return next(req); } // Кэшируем только запросы списка категорий (не товары категорий) const shouldCache = req.url.match(/\/category$/) !== null; if (!shouldCache) { return next(req); } // Cleanup expired entries before checking cleanupExpiredCache(); const cachedResponse = cache.get(req.url); // Проверяем наличие и актуальность кэша if (cachedResponse) { const age = Date.now() - cachedResponse.timestamp; if (age < CACHE_DURATION) { return of(cachedResponse.response.clone()); } else { cache.delete(req.url); } } // Выполняем запрос и кэшируем ответ return next(req).pipe( tap(event => { if (event instanceof HttpResponse) { cache.set(req.url, { response: event.clone(), timestamp: Date.now() }); } }) ); }; /** Clear all cached responses */ export function clearCache(): void { cache.clear(); } function cleanupExpiredCache(): void { const now = Date.now(); for (const [url, data] of cache.entries()) { if (now - data.timestamp >= CACHE_DURATION) { cache.delete(url); } } }