Browse Source

made the cache more persistent

master
silberengel 7 months ago
parent
commit
939759e5ce
  1. 44
      src/lib/utils/npubCache.ts

44
src/lib/utils/npubCache.ts

@ -4,6 +4,47 @@ export type NpubMetadata = NostrProfile;
class NpubCache { class NpubCache {
private cache: Record<string, NpubMetadata> = {}; private cache: Record<string, NpubMetadata> = {};
private readonly storageKey = 'alexandria_npub_cache';
private readonly maxAge = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
constructor() {
this.loadFromStorage();
}
private loadFromStorage(): void {
try {
if (typeof window !== 'undefined') {
const stored = localStorage.getItem(this.storageKey);
if (stored) {
const data = JSON.parse(stored) as Record<string, { profile: NpubMetadata; timestamp: number }>;
const now = Date.now();
// Filter out expired entries
for (const [key, entry] of Object.entries(data)) {
if (entry.timestamp && (now - entry.timestamp) < this.maxAge) {
this.cache[key] = entry.profile;
}
}
}
}
} catch (error) {
console.warn('Failed to load npub cache from storage:', error);
}
}
private saveToStorage(): void {
try {
if (typeof window !== 'undefined') {
const data: Record<string, { profile: NpubMetadata; timestamp: number }> = {};
for (const [key, profile] of Object.entries(this.cache)) {
data[key] = { profile, timestamp: Date.now() };
}
localStorage.setItem(this.storageKey, JSON.stringify(data));
}
} catch (error) {
console.warn('Failed to save npub cache to storage:', error);
}
}
get(key: string): NpubMetadata | undefined { get(key: string): NpubMetadata | undefined {
return this.cache[key]; return this.cache[key];
@ -11,6 +52,7 @@ class NpubCache {
set(key: string, value: NpubMetadata): void { set(key: string, value: NpubMetadata): void {
this.cache[key] = value; this.cache[key] = value;
this.saveToStorage();
} }
has(key: string): boolean { has(key: string): boolean {
@ -20,6 +62,7 @@ class NpubCache {
delete(key: string): boolean { delete(key: string): boolean {
if (key in this.cache) { if (key in this.cache) {
delete this.cache[key]; delete this.cache[key];
this.saveToStorage();
return true; return true;
} }
return false; return false;
@ -37,6 +80,7 @@ class NpubCache {
clear(): void { clear(): void {
this.cache = {}; this.cache = {};
this.saveToStorage();
} }
size(): number { size(): number {

Loading…
Cancel
Save