diff --git a/src/lib/cache.ts b/src/lib/cache.ts index 4be20b98f..b1950daa9 100644 --- a/src/lib/cache.ts +++ b/src/lib/cache.ts @@ -3,19 +3,20 @@ import { LRUCache } from "lru-cache"; export function cached( f: (...args: Args) => Promise, makeKey: (...args: Args) => string, - options?: LRUCache.Options, + options?: LRUCache.Options }, unknown>, ): (...args: Args) => Promise { const cache = new LRUCache(options || { max: 500 }); - return async function (...args: Args): Promise { + return function (...args: Args): Promise { const key = makeKey(...args); - const cached = cache.get(key); + const hit = cache.get(key); + if (hit !== undefined) return hit.promise; - if (cached === undefined) { - const value = await f(...args); - cache.set(key, { value }); - return value; - } else { - return cached.value; - } + const promise = f(...args); + // Evict on rejection so the next caller can retry with a fresh request. + promise.catch(() => { + cache.delete(key); + }); + cache.set(key, { promise }); + return promise; }; }