mirror of
https://github.com/better-auth/better-auth.git
synced 2026-05-22 14:21:55 -05:00
fix(api): return Response for HTTP request contexts (#7521)
This commit is contained in:
@@ -433,6 +433,19 @@ describe("after hook", async () => {
|
||||
expect(result2.headers.get("set-cookie")).toContain("session=value");
|
||||
expect(result2.headers.get("set-cookie")).toContain("data=2");
|
||||
});
|
||||
|
||||
it("should return a Response when invoked with a request context", async () => {
|
||||
const response = await authEndpoints.cookies({
|
||||
request: new Request("http://localhost:3000/cookies", {
|
||||
method: "POST",
|
||||
}),
|
||||
} as any);
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
const body = await response.json();
|
||||
expect(body).toMatchObject({ hello: "world" });
|
||||
expect(response.headers.get("set-cookie")).toContain("session=value");
|
||||
expect(response.headers.get("set-cookie")).toContain("data=2");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -120,6 +120,8 @@ export function toAuthEndpoints<const E extends Record<string, Endpoint>>(
|
||||
path: endpoint.path,
|
||||
headers: context?.headers ? new Headers(context?.headers) : undefined,
|
||||
};
|
||||
const hasRequest = context?.request instanceof Request;
|
||||
const shouldReturnResponse = context?.asResponse ?? hasRequest;
|
||||
return withSpan(
|
||||
`${methodName} ${pathName}`,
|
||||
{
|
||||
@@ -160,7 +162,7 @@ export function toAuthEndpoints<const E extends Record<string, Endpoint>>(
|
||||
internalContext = defuReplaceArrays(rest, internalContext);
|
||||
} else if (before) {
|
||||
/* Return before hook response if it's anything other than a context return */
|
||||
return context?.asResponse
|
||||
return shouldReturnResponse
|
||||
? toResponse(before, {
|
||||
headers: context?.headers,
|
||||
})
|
||||
@@ -232,11 +234,11 @@ export function toAuthEndpoints<const E extends Record<string, Endpoint>>(
|
||||
result.response.stack = result.response.errorStack;
|
||||
}
|
||||
|
||||
if (isAPIError(result.response) && !context?.asResponse) {
|
||||
if (isAPIError(result.response) && !shouldReturnResponse) {
|
||||
throw result.response;
|
||||
}
|
||||
|
||||
const response = context?.asResponse
|
||||
const response = shouldReturnResponse
|
||||
? toResponse(result.response, {
|
||||
headers: result.headers,
|
||||
status: result.status,
|
||||
|
||||
Reference in New Issue
Block a user