diff --git a/src/runtime/internal/cache.ts b/src/runtime/internal/cache.ts index 6d3d0c0c51..7a63eba22e 100644 --- a/src/runtime/internal/cache.ts +++ b/src/runtime/internal/cache.ts @@ -349,6 +349,9 @@ export function defineCachedEventHandler< fetch: globalThis.$fetch as any, })) as $Fetch; event.context = incomingEvent.context; + event.context.cache = { + options: _opts, + }; const body = (await handler(event)) || _resSendBody; // Collect cacheable headers diff --git a/src/types/h3.ts b/src/types/h3.ts index 15f851b227..651d025ace 100644 --- a/src/types/h3.ts +++ b/src/types/h3.ts @@ -1,4 +1,8 @@ -import type { CaptureError, CapturedErrorContext } from "nitropack/types"; +import type { + CaptureError, + CapturedErrorContext, + CacheOptions, +} from "nitropack/types"; import type { NitroFetchRequest, $Fetch } from "./fetch/fetch"; export type H3EventFetch = ( @@ -25,6 +29,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 413db29752..6297b947b2 100644 --- a/test/tests.ts +++ b/test/tests.ts @@ -652,7 +652,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" }), @@ -661,7 +665,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); } } );