Skip to content

Commit

Permalink
feat(defineCachedEventHandler): add event.context.cache (#2519)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <[email protected]>
  • Loading branch information
atinux and pi0 committed Jun 27, 2024
1 parent 827bedb commit 46b5a05
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 5 deletions.
3 changes: 3 additions & 0 deletions src/runtime/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,9 @@ export function defineCachedEventHandler<
fetch: globalThis.$fetch,
})) as $Fetch<unknown, NitroFetchRequest>;
event.context = incomingEvent.context;
event.context.cache = {
options: _opts,
};
const body = (await handler(event)) || _resSendBody;

// Collect cachable headers
Expand Down
6 changes: 5 additions & 1 deletion src/types/h3.ts
Original file line number Diff line number Diff line change
@@ -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 = (
Expand All @@ -25,6 +25,10 @@ declare module "h3" {
/** @experimental */
errors: { error?: Error; context: CapturedErrorContext }[];
};

cache: {
options: CacheOptions;
};
}
}

Expand Down
7 changes: 5 additions & 2 deletions test/fixture/api/cached.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export default defineCachedEventHandler(() => {
return Date.now();
export default defineCachedEventHandler((event) => {
return {
timestamp: Date.now(),
eventContextCache: event.context.cache,
};
});
9 changes: 7 additions & 2 deletions test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" }),
Expand All @@ -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);
}
}
);
Expand Down

0 comments on commit 46b5a05

Please sign in to comment.