Skip to content

Commit 2baf6dc

Browse files
authored
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.
1 parent 70d6cbd commit 2baf6dc

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

src/plugins/fs_routes/mod.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,10 @@ export async function fsRoutes<State>(
296296
isHandlerByMethod(handlers) &&
297297
!Object.keys(handlers).includes("GET");
298298
if (missingGetHandler) {
299-
app.get(routePath, renderMiddleware(components, undefined));
299+
const combined = middlewares.concat(
300+
renderMiddleware(components, undefined),
301+
);
302+
app.get(routePath, ...combined);
300303
}
301304
}
302305

src/plugins/fs_routes/mod_test.tsx

+41
Original file line numberDiff line numberDiff line change
@@ -1193,6 +1193,47 @@ Deno.test("fsRoutes - registers default GET route for component without GET hand
11931193
);
11941194
});
11951195

1196+
Deno.test("fsRoutes - default GET route works with nested middleware", async () => {
1197+
const server = await createServer<{ text: string }>({
1198+
"routes/_middleware.ts": {
1199+
handler: (ctx) => {
1200+
ctx.state.text = "A";
1201+
return ctx.next();
1202+
},
1203+
},
1204+
"routes/foo/_middleware.ts": {
1205+
handler: (ctx) => {
1206+
ctx.state.text += "B";
1207+
return ctx.next();
1208+
},
1209+
},
1210+
"routes/foo/noGetHandler.tsx": {
1211+
default: (ctx) => {
1212+
return <h1>{ctx.state.text}</h1>;
1213+
},
1214+
handlers: {
1215+
POST: () => new Response("POST"),
1216+
},
1217+
},
1218+
});
1219+
1220+
const postRes = await server.post("/foo/noGetHandler");
1221+
expect(postRes.status).toEqual(200);
1222+
expect(postRes.headers.get("Content-Type")).toEqual(
1223+
"text/plain;charset=UTF-8",
1224+
);
1225+
expect(await postRes.text()).toEqual("POST");
1226+
1227+
const getRes = await server.get("/foo/noGetHandler");
1228+
expect(getRes.status).toEqual(200);
1229+
expect(getRes.headers.get("Content-Type")).toEqual(
1230+
"text/html; charset=utf-8",
1231+
);
1232+
expect(await getRes.text()).toContain(
1233+
"<h1>AB</h1>",
1234+
);
1235+
});
1236+
11961237
Deno.test("fsRoutes - default GET route doesn't override existing handler", async () => {
11971238
const server = await createServer<{ value: boolean }>({
11981239
"routes/withGetHandler.tsx": {

0 commit comments

Comments
 (0)