work version archive
This commit is contained in:
10
src/lib/cache/cache-ttl.ts
vendored
Normal file
10
src/lib/cache/cache-ttl.ts
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Конфигурация TTL из .env с fallback значениями
|
||||
*/
|
||||
export const CACHE_TTL = {
|
||||
TAXONOMY: parseInt(import.meta.env.CACHE_TAXONOMY_TTL || '3600'),
|
||||
POSTS: parseInt(import.meta.env.CACHE_POST_TTL || '1800')
|
||||
} as const;
|
||||
|
||||
// Для отключения кэша
|
||||
//export const CACHE_DISABLED = 0;
|
||||
77
src/lib/cache/manager.ts
vendored
Normal file
77
src/lib/cache/manager.ts
vendored
Normal file
@@ -0,0 +1,77 @@
|
||||
export interface CacheOptions {
|
||||
ttl: number; // время жизни в секундах, 0 = не кешировать
|
||||
}
|
||||
|
||||
export interface CacheEntry<T> {
|
||||
data: T;
|
||||
expires: number; // timestamp в миллисекундах
|
||||
}
|
||||
|
||||
export class CacheManager {
|
||||
private store = new Map<string, CacheEntry<any>>();
|
||||
|
||||
async wrap<T>(
|
||||
key: string,
|
||||
fetchFn: () => Promise<T>,
|
||||
options: { ttl: number } = { ttl: 300 }
|
||||
): Promise<T> {
|
||||
// Если ttl = 0, пропускаем кеширование
|
||||
if (options.ttl <= 0) {
|
||||
//console.log('Cache SKIP (ttl=0):', key);
|
||||
return await fetchFn();
|
||||
}
|
||||
|
||||
const cached = this.store.get(key);
|
||||
|
||||
// Проверяем TTL
|
||||
if (cached && cached.expires > Date.now()) {
|
||||
console.log('Cache HIT:', key);
|
||||
return cached.data;
|
||||
}
|
||||
|
||||
//console.log('Cache MISS:', key);
|
||||
const data = await fetchFn();
|
||||
|
||||
// Сохраняем с TTL
|
||||
this.store.set(key, {
|
||||
data,
|
||||
expires: Date.now() + (options.ttl * 1000)
|
||||
});
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// Дополнительные методы для управления кешем
|
||||
get<T>(key: string): T | null {
|
||||
const entry = this.store.get(key);
|
||||
if (!entry || entry.expires <= Date.now()) {
|
||||
return null;
|
||||
}
|
||||
return entry.data;
|
||||
}
|
||||
|
||||
set<T>(key: string, value: T, ttl: number): void {
|
||||
if (ttl <= 0) return;
|
||||
|
||||
this.store.set(key, {
|
||||
data: value,
|
||||
expires: Date.now() + (ttl * 1000)
|
||||
});
|
||||
}
|
||||
|
||||
delete(key: string): boolean {
|
||||
return this.store.delete(key);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
has(key: string): boolean {
|
||||
const entry = this.store.get(key);
|
||||
return !!entry && entry.expires > Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
// Экспортируем синглтон для использования
|
||||
export const cache = new CacheManager();
|
||||
Reference in New Issue
Block a user