Skip to content

Commit

Permalink
fix: middleware default export ignored (#2680)
Browse files Browse the repository at this point in the history
Fixes #2657
  • Loading branch information
marvinhagemeister authored Oct 4, 2024
1 parent 73b0398 commit 5f65747
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/plugins/fs_routes/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,15 @@ export async function fsRoutes<State>(
routePath.slice(0, routePath.lastIndexOf("."))
}`;
const base = normalizedPath.slice(0, normalizedPath.lastIndexOf("/"));
const isMiddleware = normalizedPath.endsWith("/_middleware");
return {
path: normalizedPath,
filePath: routePath,
base,
handlers: mod.handlers ?? mod.handler ?? null,
handlers: mod.handlers ?? mod.handler ??
(isMiddleware ? mod.default ?? null : null),
config: mod.config ?? null,
component: mod.default ?? null,
component: isMiddleware ? null : mod.default ?? null,
} as InternalRoute<State>;
}),
);
Expand Down
18 changes: 18 additions & 0 deletions src/plugins/fs_routes/mod_test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { expect } from "@std/expect";
import { type HandlerByMethod, type HandlerFn, page } from "../../handlers.ts";
import type { Method } from "../../router.ts";
import { parseHtml } from "../../../tests/test_utils.tsx";
import type { FreshContext } from "fresh";

async function createServer<T>(
files: Record<string, string | Uint8Array | FreshFsItem<T>>,
Expand Down Expand Up @@ -171,6 +172,23 @@ Deno.test("fsRoutes - add middleware for function handler", async () => {
expect(doc.body.firstChild?.textContent).toEqual("ok");
});

Deno.test("fsRoutes - middleware", async () => {
const server = await createServer<{ text: string }>({
"routes/index.ts": { handler: (ctx) => new Response(ctx.state.text) },
"routes/_middleware.ts": {
default: ((ctx: FreshContext<{ text: string }>) => {
ctx.state.text = "ok";
return ctx.next();
// deno-lint-ignore no-explicit-any
}) as any,
},
});

const res = await server.get("/");
expect(res.status).toEqual(200);
expect(await res.text()).toEqual("ok");
});

Deno.test("fsRoutes - nested middlewares", async () => {
const server = await createServer<{ text: string }>({
"routes/_middleware.ts": {
Expand Down

0 comments on commit 5f65747

Please sign in to comment.