This commit is contained in:
sdarbinyan
2026-03-06 18:40:58 +04:00
parent c3e4e695eb
commit 0b3b2ee463
25 changed files with 253 additions and 165 deletions

View File

@@ -2,8 +2,9 @@ import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CACHE_DURATION_MS, CATEGORY_CACHE_DURATION_MS } from '../config/constants';
const cache = new Map<string, { response: HttpResponse<unknown>, timestamp: number }>();
const CACHE_DURATION = 5 * 60 * 1000; // 5 минут
export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
// Кэшируем только GET запросы
@@ -11,12 +12,16 @@ export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
return next(req);
}
// Кэшируем только запросы списка категорий (не товары категорий)
const shouldCache = req.url.match(/\/category$/) !== null;
if (!shouldCache) {
// Кэшируем списки категорий, товары категорий и отдельные товары
const isCategoryList = /\/category$/.test(req.url);
const isCategoryItems = /\/category\/\d+/.test(req.url);
const isItem = /\/item\/\d+/.test(req.url);
if (!isCategoryList && !isCategoryItems && !isItem) {
return next(req);
}
const ttl = isCategoryList ? CACHE_DURATION_MS : CATEGORY_CACHE_DURATION_MS;
// Cleanup expired entries before checking
cleanupExpiredCache();
@@ -25,7 +30,7 @@ export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
// Проверяем наличие и актуальность кэша
if (cachedResponse) {
const age = Date.now() - cachedResponse.timestamp;
if (age < CACHE_DURATION) {
if (age < ttl) {
return of(cachedResponse.response.clone());
} else {
cache.delete(req.url);
@@ -53,7 +58,7 @@ export function clearCache(): void {
function cleanupExpiredCache(): void {
const now = Date.now();
for (const [url, data] of cache.entries()) {
if (now - data.timestamp >= CACHE_DURATION) {
if (now - data.timestamp >= CACHE_DURATION_MS) {
cache.delete(url);
}
}