Files
marketplaces/src/app/interceptors/cache.interceptor.ts

61 lines
1.6 KiB
TypeScript
Raw Normal View History

2026-01-18 18:57:06 +04:00
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
2026-02-26 21:54:21 +04:00
const cache = new Map<string, { response: HttpResponse<unknown>, timestamp: number }>();
2026-01-18 18:57:06 +04:00
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);
}
2026-02-26 21:54:21 +04:00
// Cleanup expired entries before checking
cleanupExpiredCache();
2026-01-18 18:57:06 +04:00
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()
});
}
})
);
};
2026-02-26 21:54:21 +04:00
/** Clear all cached responses */
2026-01-18 18:57:06 +04:00
export function clearCache(): void {
cache.clear();
}
2026-02-26 21:54:21 +04:00
function cleanupExpiredCache(): void {
2026-01-18 18:57:06 +04:00
const now = Date.now();
for (const [url, data] of cache.entries()) {
if (now - data.timestamp >= CACHE_DURATION) {
cache.delete(url);
}
}
}