From 2baf6dc7a0c238a6da8d4a00a4eace461ebce79d Mon Sep 17 00:00:00 2001 From: Paul Carduner Date: Wed, 8 Jan 2025 15:09:26 -0800 Subject: [PATCH] fix: middlewares not being used with default GET handlers (#2807) I noticed a small bug with the default GET handlers where middlewares were not being run. This pull requests fixes the bug and adds some unit tests for this behavior. --- src/plugins/fs_routes/mod.ts | 5 +++- src/plugins/fs_routes/mod_test.tsx | 41 ++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/plugins/fs_routes/mod.ts b/src/plugins/fs_routes/mod.ts index 7e9cb6c5..46a92f26 100644 --- a/src/plugins/fs_routes/mod.ts +++ b/src/plugins/fs_routes/mod.ts @@ -296,7 +296,10 @@ export async function fsRoutes( isHandlerByMethod(handlers) && !Object.keys(handlers).includes("GET"); if (missingGetHandler) { - app.get(routePath, renderMiddleware(components, undefined)); + const combined = middlewares.concat( + renderMiddleware(components, undefined), + ); + app.get(routePath, ...combined); } } diff --git a/src/plugins/fs_routes/mod_test.tsx b/src/plugins/fs_routes/mod_test.tsx index 261a2dec..27606892 100644 --- a/src/plugins/fs_routes/mod_test.tsx +++ b/src/plugins/fs_routes/mod_test.tsx @@ -1193,6 +1193,47 @@ Deno.test("fsRoutes - registers default GET route for component without GET hand ); }); +Deno.test("fsRoutes - default GET route works with nested middleware", async () => { + const server = await createServer<{ text: string }>({ + "routes/_middleware.ts": { + handler: (ctx) => { + ctx.state.text = "A"; + return ctx.next(); + }, + }, + "routes/foo/_middleware.ts": { + handler: (ctx) => { + ctx.state.text += "B"; + return ctx.next(); + }, + }, + "routes/foo/noGetHandler.tsx": { + default: (ctx) => { + return

{ctx.state.text}

; + }, + handlers: { + POST: () => new Response("POST"), + }, + }, + }); + + const postRes = await server.post("/foo/noGetHandler"); + expect(postRes.status).toEqual(200); + expect(postRes.headers.get("Content-Type")).toEqual( + "text/plain;charset=UTF-8", + ); + expect(await postRes.text()).toEqual("POST"); + + const getRes = await server.get("/foo/noGetHandler"); + expect(getRes.status).toEqual(200); + expect(getRes.headers.get("Content-Type")).toEqual( + "text/html; charset=utf-8", + ); + expect(await getRes.text()).toContain( + "

AB

", + ); +}); + Deno.test("fsRoutes - default GET route doesn't override existing handler", async () => { const server = await createServer<{ value: boolean }>({ "routes/withGetHandler.tsx": {