very first commit
This commit is contained in:
63
src/app/interceptors/cache.interceptor.ts
Normal file
63
src/app/interceptors/cache.interceptor.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
|
||||
import { of } from 'rxjs';
|
||||
import { tap } from 'rxjs/operators';
|
||||
|
||||
const cache = new Map<string, { response: HttpResponse<any>, 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);
|
||||
}
|
||||
|
||||
const cachedResponse = cache.get(req.url);
|
||||
|
||||
// Проверяем наличие и актуальность кэша
|
||||
if (cachedResponse) {
|
||||
const age = Date.now() - cachedResponse.timestamp;
|
||||
if (age < CACHE_DURATION) {
|
||||
// console.log(`[Cache] Returning cached response for: ${req.url}`);
|
||||
return of(cachedResponse.response.clone());
|
||||
} else {
|
||||
// Кэш устарел, удаляем
|
||||
cache.delete(req.url);
|
||||
}
|
||||
}
|
||||
|
||||
// Выполняем запрос и кэшируем ответ
|
||||
return next(req).pipe(
|
||||
tap(event => {
|
||||
if (event instanceof HttpResponse) {
|
||||
// console.log(`[Cache] Caching response for: ${req.url}`);
|
||||
cache.set(req.url, {
|
||||
response: event.clone(),
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
// Функция для очистки кэша (можно использовать при необходимости)
|
||||
export function clearCache(): void {
|
||||
cache.clear();
|
||||
// console.log('[Cache] Cache cleared');
|
||||
}
|
||||
|
||||
// Функция для очистки устаревшего кэша
|
||||
export function cleanupExpiredCache(): void {
|
||||
const now = Date.now();
|
||||
for (const [url, data] of cache.entries()) {
|
||||
if (now - data.timestamp >= CACHE_DURATION) {
|
||||
cache.delete(url);
|
||||
}
|
||||
}
|
||||
// console.log('[Cache] Expired cache cleaned up');
|
||||
}
|
||||
Reference in New Issue
Block a user