(
pipeline: string,
searchRequest: unknown,
ctx: { waitUntil: (p: Promise<unknown>) => void },
fetcher: () => Promise<T>,
)
| 369 | * so any change to query / filters / ranking options invalidates automatically. |
| 370 | */ |
| 371 | export async function withAutoragCache<T>( |
| 372 | pipeline: string, |
| 373 | searchRequest: unknown, |
| 374 | ctx: { waitUntil: (p: Promise<unknown>) => void }, |
| 375 | fetcher: () => Promise<T>, |
| 376 | ): Promise<T> { |
| 377 | const keyHash = await sha256Hex( |
| 378 | JSON.stringify({ pipeline, request: searchRequest }), |
| 379 | ); |
| 380 | const cacheRequest = buildAutoragCacheRequest(pipeline, keyHash); |
| 381 | const cache = caches.default; |
| 382 | |
| 383 | try { |
| 384 | const cached = await cache.match(cacheRequest); |
| 385 | if (cached) { |
| 386 | return (await cached.json()) as T; |
| 387 | } |
| 388 | } catch (error) { |
| 389 | console.warn("AutoRAG cache lookup failed:", error); |
| 390 | } |
| 391 | |
| 392 | const answer = await fetcher(); |
| 393 | |
| 394 | try { |
| 395 | const response = new Response(JSON.stringify(answer), { |
| 396 | headers: { |
| 397 | "Content-Type": "application/json", |
| 398 | "Cache-Control": `public, max-age=${AUTORAG_CACHE_TTL}`, |
| 399 | }, |
| 400 | }); |
| 401 | ctx.waitUntil(cache.put(cacheRequest, response)); |
| 402 | } catch (error) { |
| 403 | console.warn("AutoRAG cache write failed:", error); |
| 404 | } |
| 405 | |
| 406 | return answer; |
| 407 | } |
no test coverage detected