Skip to content

Commit

Permalink
fix(cache): set cache item before returning response on first request (
Browse files Browse the repository at this point in the history
  • Loading branch information
yassilah authored Oct 19, 2023
1 parent 3e9302a commit bfe1eaa
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/runtime/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,9 @@ export function defineCachedFunction<T, ArgsT extends unknown[] = unknown[]>(

const _resolvePromise = expired ? _resolve() : Promise.resolve();

if (expired && event && event.waitUntil) {
if (entry.value === undefined) {
await _resolvePromise;
} else if (expired && event && event.waitUntil) {
event.waitUntil(_resolvePromise);
}

Expand Down
3 changes: 3 additions & 0 deletions test/fixture/api/cached.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default defineCachedEventHandler(() => {
return Date.now();
});
16 changes: 16 additions & 0 deletions test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -601,4 +601,20 @@ export function testNitro(
expect(data.runtimeConfig.secret).toBeUndefined();
});
});

describe("cache", () => {
it("should setItem before returning response the first time", async () => {
const { data: timestamp } = await callHandler({ url: "/api/cached" });

const calls = await Promise.all([
callHandler({ url: "/api/cached" }),
callHandler({ url: "/api/cached" }),
callHandler({ url: "/api/cached" }),
]);

for (const call of calls) {
expect(call.data).toBe(timestamp);
}
});
});
}

0 comments on commit bfe1eaa

Please sign in to comment.