← Files Sulekha EventsARCHIVED FILE
source/src/data/search-cache.js
1016 Bytes · Nov 30, 2026 · 07:53 UTC
// Share identical concurrent requests and briefly reuse successful responses.
// Include rawQuery and platform so original-message reporting stays accurate.
export function createSearchCache(search, { ttl = 10000, maxEntries = 100, now = Date.now } = {}) {
const cached = new Map();
const pending = new Map();
return async (args, options = {}) => {
const key = JSON.stringify([Object.keys(args).sort().map(key => [key, args[key]]), options.platform]);
const hit = cached.get(key);
if (hit && hit.expires > now()) return structuredClone(hit.value);
if (pending.has(key)) return structuredClone(await pending.get(key));
const request = Promise.resolve().then(() => search(args, options));
pending.set(key, request);
try {
const value = await request;
if (cached.size >= maxEntries) cached.delete(cached.keys().next().value);
cached.set(key, { value: structuredClone(value), expires: now() + ttl });
return value;
} finally { pending.delete(key); }
};
}
SHA-256: 6529588350e3d40207b3f87f37f963922fe7278f1ab42e86cf6cee88cf7e6550