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 <pooya@pi0.io>
  • Loading branch information
atinux and pi0 committed Jun 13, 2024
1 parent 178f209 commit fc3968b
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 5 deletions.
3 changes: 3 additions & 0 deletions src/runtime/internal/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ export function defineCachedEventHandler<
fetch: globalThis.$fetch as any,
})) as $Fetch<unknown, NitroFetchRequest>;
event.context = incomingEvent.context;
event.context.cache = {
options: _opts,
};
const body = (await handler(event)) || _resSendBody;

// Collect cacheable headers
Expand Down
10 changes: 9 additions & 1 deletion src/types/h3.ts
Original file line number Diff line number Diff line change
@@ -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 = (
Expand All @@ -25,6 +29,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 @@ -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" }),
Expand All @@ -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);
}
}
);
Expand Down

0 comments on commit fc3968b

Please sign in to comment.