From de06613eeb152360a92d8c45ba1331eff6b35adc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C5=ABdolfs=20O=C5=A1i=C5=86=C5=A1?= Date: Fri, 24 Apr 2026 17:07:28 +0200 Subject: [PATCH] Dedupe in-flight requests in cached() --- src/lib/cached.ts | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/lib/cached.ts b/src/lib/cached.ts index 4be20b98f..b1950daa9 100644 --- a/src/lib/cached.ts +++ b/src/lib/cached.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; }; }