Files
immich-folio/lib/cache.ts

57 lines
1.3 KiB
TypeScript
Raw Normal View History

/**
* Simple in-memory LRU cache for Immich API responses.
* Avoids hammering the Immich server with identical requests.
*/
interface CacheEntry<T> {
data: T;
expiresAt: number;
}
class MemoryCache {
private store = new Map<string, CacheEntry<unknown>>();
private maxEntries = 200;
get<T>(key: string): T | null {
const entry = this.store.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
this.store.delete(key);
return null;
}
// LRU: Move accessed item to the back of the Map (newest)
this.store.delete(key);
this.store.set(key, entry);
return entry.data as T;
}
set<T>(key: string, data: T, ttlMs: number): void {
// If key exists, delete it first to ensure we push it to the back
if (this.store.has(key)) {
this.store.delete(key);
} else if (this.store.size >= this.maxEntries) {
// Evict oldest entry (first item) if at capacity
const firstKey = this.store.keys().next().value;
if (firstKey) this.store.delete(firstKey);
}
this.store.set(key, {
data,
expiresAt: Date.now() + ttlMs,
});
}
delete(key: string): void {
this.store.delete(key);
}
clear(): void {
this.store.clear();
}
}
export const cache = new MemoryCache();