mirror of
https://github.com/better-auth/better-auth.git
synced 2026-05-23 07:18:56 -05:00
fix: await ctx in middleware (#3783)
* fix: await ctx in middleware * fix: lint * Create tidy-impalas-fail.md
This commit is contained in:
5
.changeset/tidy-impalas-fail.md
Normal file
5
.changeset/tidy-impalas-fail.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"better-auth": patch
|
||||
---
|
||||
|
||||
fix: await `ctx` in middleware
|
||||
54
packages/better-auth/src/api/index.test.ts
Normal file
54
packages/better-auth/src/api/index.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { getEndpoints } from "./index";
|
||||
import type { AuthContext } from "../init";
|
||||
import type { BetterAuthOptions, BetterAuthPlugin } from "../types";
|
||||
import { createAuthMiddleware } from "./call";
|
||||
|
||||
describe("getEndpoints", () => {
|
||||
it("should await promise-based context before passing to middleware", async () => {
|
||||
const mockContext: AuthContext = {
|
||||
baseURL: "http://localhost:3000",
|
||||
options: {},
|
||||
} as any;
|
||||
|
||||
const middlewareFn = vi.fn().mockResolvedValue({});
|
||||
|
||||
const testPlugin: BetterAuthPlugin = {
|
||||
id: "test-plugin",
|
||||
middlewares: [
|
||||
{
|
||||
path: "/test",
|
||||
middleware: createAuthMiddleware(async (ctx) => {
|
||||
middlewareFn(ctx);
|
||||
return {};
|
||||
}),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const options: BetterAuthOptions = {
|
||||
plugins: [testPlugin],
|
||||
};
|
||||
|
||||
const promiseContext = new Promise<AuthContext>((resolve) => {
|
||||
setTimeout(() => resolve(mockContext), 10);
|
||||
});
|
||||
|
||||
const { middlewares } = getEndpoints(promiseContext, options);
|
||||
|
||||
const testCtx = {
|
||||
request: new Request("http://localhost:3000/test"),
|
||||
context: { customProp: "value" },
|
||||
};
|
||||
|
||||
await middlewares[0].middleware(testCtx);
|
||||
|
||||
expect(middlewareFn).toHaveBeenCalled();
|
||||
const call = middlewareFn.mock.calls[0][0];
|
||||
expect(call.context).toMatchObject({
|
||||
baseURL: "http://localhost:3000",
|
||||
options: {},
|
||||
customProp: "value",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -72,10 +72,11 @@ export function getEndpoints<
|
||||
?.map((plugin) =>
|
||||
plugin.middlewares?.map((m) => {
|
||||
const middleware = (async (context: any) => {
|
||||
const authContext = await ctx;
|
||||
return m.middleware({
|
||||
...context,
|
||||
context: {
|
||||
...ctx,
|
||||
...authContext,
|
||||
...context.context,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user