Skip to content

Commit 46b5a05

Browse files
atinuxpi0
andcommitted
feat(defineCachedEventHandler): add event.context.cache (#2519)
Co-authored-by: Pooya Parsa <[email protected]>
1 parent 827bedb commit 46b5a05

File tree

4 files changed

+20
-5
lines changed

4 files changed

+20
-5
lines changed

src/runtime/cache.ts

+3
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,9 @@ export function defineCachedEventHandler<
370370
fetch: globalThis.$fetch,
371371
})) as $Fetch<unknown, NitroFetchRequest>;
372372
event.context = incomingEvent.context;
373+
event.context.cache = {
374+
options: _opts,
375+
};
373376
const body = (await handler(event)) || _resSendBody;
374377

375378
// Collect cachable headers

src/types/h3.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { CaptureError, CapturedErrorContext } from "../runtime/types";
1+
import type { CacheOptions, CaptureError, CapturedErrorContext } from "../runtime/types";
22
import type { NitroFetchRequest, $Fetch } from "./fetch";
33

44
export type H3EventFetch = (
@@ -25,6 +25,10 @@ declare module "h3" {
2525
/** @experimental */
2626
errors: { error?: Error; context: CapturedErrorContext }[];
2727
};
28+
29+
cache: {
30+
options: CacheOptions;
31+
};
2832
}
2933
}
3034

test/fixture/api/cached.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1-
export default defineCachedEventHandler(() => {
2-
return Date.now();
1+
export default defineCachedEventHandler((event) => {
2+
return {
3+
timestamp: Date.now(),
4+
eventContextCache: event.context.cache,
5+
};
36
});

test/tests.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,11 @@ export function testNitro(
643643
it.skipIf(ctx.isIsolated)(
644644
"should setItem before returning response the first time",
645645
async () => {
646-
const { data: timestamp } = await callHandler({ url: "/api/cached" });
646+
const {
647+
data: { timestamp, eventContextCache },
648+
} = await callHandler({ url: "/api/cached" });
649+
650+
expect(eventContextCache?.options.swr).toBe(true);
647651

648652
const calls = await Promise.all([
649653
callHandler({ url: "/api/cached" }),
@@ -652,7 +656,8 @@ export function testNitro(
652656
]);
653657

654658
for (const call of calls) {
655-
expect(call.data).toBe(timestamp);
659+
expect(call.data.timestamp).toBe(timestamp);
660+
expect(call.data.eventContextCache.options.swr).toBe(true);
656661
}
657662
}
658663
);

0 commit comments

Comments
 (0)