2026-02-14 00:59:57 +01:00
|
|
|
/**
|
|
|
|
|
* Simple in-memory LRU cache for Immich API responses.
|
|
|
|
|
* Avoids hammering the Immich server with identical requests.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
interface CacheEntry<T> {
|
2026-02-14 11:47:26 +01:00
|
|
|
data: T;
|
|
|
|
|
expiresAt: number;
|
2026-02-14 00:59:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class MemoryCache {
|
2026-02-14 11:47:26 +01:00
|
|
|
private store = new Map<string, CacheEntry<unknown>>();
|
|
|
|
|
private maxEntries = 200;
|
2026-02-14 00:59:57 +01:00
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
get<T>(key: string): T | null {
|
|
|
|
|
const entry = this.store.get(key);
|
|
|
|
|
if (!entry) return null;
|
2026-02-14 00:59:57 +01:00
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
if (Date.now() > entry.expiresAt) {
|
|
|
|
|
this.store.delete(key);
|
|
|
|
|
return null;
|
2026-02-14 00:59:57 +01:00
|
|
|
}
|
|
|
|
|
|
2026-03-27 11:11:23 +01:00
|
|
|
// LRU: Move accessed item to the back of the Map (newest)
|
|
|
|
|
this.store.delete(key);
|
|
|
|
|
this.store.set(key, entry);
|
|
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
return entry.data as T;
|
|
|
|
|
}
|
2026-02-14 00:59:57 +01:00
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
set<T>(key: string, data: T, ttlMs: number): void {
|
2026-03-27 11:11:23 +01:00
|
|
|
// 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
|
2026-02-14 11:47:26 +01:00
|
|
|
const firstKey = this.store.keys().next().value;
|
|
|
|
|
if (firstKey) this.store.delete(firstKey);
|
2026-02-14 00:59:57 +01:00
|
|
|
}
|
2026-02-14 11:47:26 +01:00
|
|
|
|
|
|
|
|
this.store.set(key, {
|
|
|
|
|
data,
|
|
|
|
|
expiresAt: Date.now() + ttlMs,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-29 17:04:57 +02:00
|
|
|
delete(key: string): void {
|
|
|
|
|
this.store.delete(key);
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-14 11:47:26 +01:00
|
|
|
clear(): void {
|
|
|
|
|
this.store.clear();
|
|
|
|
|
}
|
2026-02-14 00:59:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const cache = new MemoryCache();
|