This commit is contained in:
Michael Freno
2025-12-23 10:23:43 -05:00
parent ee1de16c9e
commit 236555e41e
12 changed files with 20 additions and 210 deletions

View File

@@ -19,17 +19,11 @@ class SimpleCache {
return entry.data as T;
}
/**
* Get cached data even if expired (for stale-while-revalidate)
*/
getStale<T>(key: string): T | null {
const entry = this.cache.get(key);
return entry ? (entry.data as T) : null;
}
/**
* Check if cache entry exists (regardless of expiration)
*/
has(key: string): boolean {
return this.cache.has(key);
}
@@ -49,9 +43,6 @@ class SimpleCache {
this.cache.delete(key);
}
/**
* Delete all keys starting with a prefix
*/
deleteByPrefix(prefix: string): void {
for (const key of this.cache.keys()) {
if (key.startsWith(prefix)) {
@@ -62,8 +53,6 @@ class SimpleCache {
}
export const cache = new SimpleCache();
// Helper function to wrap async operations with caching
export async function withCache<T>(
key: string,
ttlMs: number,
@@ -80,7 +69,6 @@ export async function withCache<T>(
}
/**
* Cache wrapper with stale-while-revalidate support
* Returns stale data if fetch fails, with optional stale time limit
*/
export async function withCacheAndStale<T>(
@@ -88,19 +76,17 @@ export async function withCacheAndStale<T>(
ttlMs: number,
fn: () => Promise<T>,
options: {
maxStaleMs?: number; // Maximum age of stale data to return (default: 7 days)
logErrors?: boolean; // Whether to log errors (default: true)
maxStaleMs?: number;
logErrors?: boolean;
} = {}
): Promise<T> {
const { maxStaleMs = 7 * 24 * 60 * 60 * 1000, logErrors = true } = options;
// Try to get fresh cached data
const cached = cache.get<T>(key, ttlMs);
if (cached !== null) {
return cached;
}
// Try to fetch new data
try {
const result = await fn();
cache.set(key, result);
@@ -110,10 +96,8 @@ export async function withCacheAndStale<T>(
console.error(`Error fetching data for cache key "${key}":`, error);
}
// If fetch fails, try to serve stale data
const stale = cache.getStale<T>(key);
if (stale !== null) {
// Check if stale data is within acceptable age
const entry = (cache as any).cache.get(key);
const age = Date.now() - entry.timestamp;
@@ -127,7 +111,6 @@ export async function withCacheAndStale<T>(
}
}
// No stale data available or too old, re-throw the error
throw error;
}
}