diff --git a/src/runtime/cache.ts b/src/runtime/cache.ts index 25a230c971..635a747adb 100644 --- a/src/runtime/cache.ts +++ b/src/runtime/cache.ts @@ -370,6 +370,9 @@ export function defineCachedEventHandler< fetch: globalThis.$fetch, })) as $Fetch; event.context = incomingEvent.context; + event.context.cache = { + options: _opts, + }; const body = (await handler(event)) || _resSendBody; // Collect cachable headers diff --git a/src/types/h3.ts b/src/types/h3.ts index 115226aae4..44d4056b94 100644 --- a/src/types/h3.ts +++ b/src/types/h3.ts @@ -1,4 +1,4 @@ -import type { CaptureError, CapturedErrorContext } from "../runtime/types"; +import type { CacheOptions, CaptureError, CapturedErrorContext } from "../runtime/types"; import type { NitroFetchRequest, $Fetch } from "./fetch"; export type H3EventFetch = ( @@ -25,6 +25,10 @@ declare module "h3" { /** @experimental */ errors: { error?: Error; context: CapturedErrorContext }[]; }; + + cache: { + options: CacheOptions; + }; } } diff --git a/test/fixture/api/cached.ts b/test/fixture/api/cached.ts index 83d2fce264..0b76b1b512 100644 --- a/test/fixture/api/cached.ts +++ b/test/fixture/api/cached.ts @@ -1,3 +1,6 @@ -export default defineCachedEventHandler(() => { - return Date.now(); +export default defineCachedEventHandler((event) => { + return { + timestamp: Date.now(), + eventContextCache: event.context.cache, + }; }); diff --git a/test/tests.ts b/test/tests.ts index b3bc6dd9f7..eda072dbc9 100644 --- a/test/tests.ts +++ b/test/tests.ts @@ -643,7 +643,11 @@ export function testNitro( it.skipIf(ctx.isIsolated)( "should setItem before returning response the first time", async () => { - const { data: timestamp } = await callHandler({ url: "/api/cached" }); + const { + data: { timestamp, eventContextCache }, + } = await callHandler({ url: "/api/cached" }); + + expect(eventContextCache?.options.swr).toBe(true); const calls = await Promise.all([ callHandler({ url: "/api/cached" }), @@ -652,7 +656,8 @@ export function testNitro( ]); for (const call of calls) { - expect(call.data).toBe(timestamp); + expect(call.data.timestamp).toBe(timestamp); + expect(call.data.eventContextCache.options.swr).toBe(true); } } );