Skip to content

Commit 8572374

Browse files
committed
fix: Only call onGlobalAfterResponse once
1 parent 2f47650 commit 8572374

2 files changed

Lines changed: 12 additions & 4 deletions

File tree

src/internal/__tests__/compile-fetch-function.test.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ describe("compileFetchFunction", () => {
147147
"(request) => {
148148
const path = utils.getRawPathname(request);
149149
const ctx = new utils.Context(request, path, utils.origin);
150+
let handlerReturnedPromise = false;
150151
151152
try {
152153
const matchedRoute = utils.getRoute(request.method, path);
@@ -162,6 +163,7 @@ describe("compileFetchFunction", () => {
162163
ctx.response = matchedRoute.data.compiledHandler(request, ctx);
163164
if (typeof ctx.response.then !== utils.FUNCTION) return ctx.response;
164165
166+
handlerReturnedPromise = true;
165167
return ctx.response.catch(error => {
166168
const status =
167169
error instanceof utils.HttpError
@@ -190,9 +192,11 @@ describe("compileFetchFunction", () => {
190192
)
191193
);
192194
} finally {
193-
setTimeout(() => {
194-
utils.hooks.onGlobalAfterResponse[0].callback(ctx);
195-
})
195+
if (!handlerReturnedPromise) {
196+
setTimeout(() => {
197+
utils.hooks.onGlobalAfterResponse[0].callback(ctx);
198+
})
199+
}
196200
}
197201
198202
}"

src/internal/compile-fetch-function.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export function compileFetchFunction(options: CompileOptions): ServerSideFetch {
1919
return (request) => {
2020
const path = utils.getRawPathname(request);
2121
const ctx = new utils.Context(request, path, utils.origin);
22+
${onGlobalAfterResponseCount ? "let handlerReturnedPromise = false;" : ""}
2223
2324
try {
2425
${onGlobalRequestCount ? compileOnGlobalRequestHook(onGlobalRequestCount) : ""}
@@ -36,6 +37,7 @@ ${onGlobalRequestCount ? compileOnGlobalRequestHook(onGlobalRequestCount) : ""}
3637
ctx.response = matchedRoute.data.compiledHandler(request, ctx);
3738
if (typeof ctx.response.then !== utils.FUNCTION) return ctx.response;
3839
40+
${onGlobalAfterResponseCount ? "handlerReturnedPromise = true;" : ""}
3941
return ctx.response.catch(error => {
4042
${onGlobalErrorCount ? compileOnGlobalErrorHook(onGlobalErrorCount, 3) : ""}
4143
@@ -105,7 +107,9 @@ function compileOnGlobalAfterResponseFinally(
105107
): string {
106108
const indent = " ".repeat(tabs);
107109
return `finally {
108-
${compileOnGlobalAfterResponseHook(hookCount, tabs + 1)}
110+
${indent} if (!handlerReturnedPromise) {
111+
${compileOnGlobalAfterResponseHook(hookCount, tabs + 2)}
112+
${indent} }
109113
${indent}}
110114
`;
111115
}

0 commit comments

Comments
 (0)