Skip to content

Commit

Permalink
fix: middleware composition
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Mar 27, 2024
1 parent 68502f4 commit 03cdf62
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
18 changes: 14 additions & 4 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,22 @@ export class FreshApp<State> implements App<State> {
mountApp(path: string, app: App<State>): this {
const routes = app._router._routes;

for (let i = 0; i < routes.length; i++) {
let middlewares: Middleware<State>[] = [];
let start = 0;
if (
routes.length > 0 && routes[0].path === "*" && routes[0].method === "ALL"
) {
start++;
middlewares = routes[0].handlers;
}

for (let i = start; i < routes.length; i++) {
const route = routes[i];

const merged = typeof route.path === "string"
? mergePaths(path, route.path)
: route.path;
const combined = this.#middlewares.concat(route.handlers);
const combined = middlewares.concat(route.handlers);
this._router.add(route.method, merged, combined);
}

Expand All @@ -141,8 +150,9 @@ export class FreshApp<State> implements App<State> {
): this {
if (!this.#addedMiddlewares) {
this.#addedMiddlewares = true;
// FIXME: Composing with basepath/apps
this._router.add("ALL", "*", this.#middlewares);
if (this.#middlewares.length > 0) {
this._router.add("ALL", "*", this.#middlewares);
}
}
const merged = typeof pathname === "string"
? mergePaths(this.config.basePath, pathname)
Expand Down
11 changes: 8 additions & 3 deletions src/app_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ Deno.test("FreshApp - methods with middleware", async () => {
expect(await res.text()).toEqual("A");
});

Deno.test("FreshApp - .route() compose apps", async () => {
Deno.test("FreshApp - .mountApp() compose apps", async () => {
const innerApp = new FreshApp<{ text: string }>()
.use((ctx) => {
ctx.state.text = "A";
Expand All @@ -244,11 +244,16 @@ Deno.test("FreshApp - .route() compose apps", async () => {
.get("/", (ctx) => new Response(ctx.state.text))
.post("/", (ctx) => new Response(ctx.state.text));

const app = new FreshApp<{ text: string }>().mountApp("/foo", innerApp);
const app = new FreshApp<{ text: string }>()
.get("/", () => new Response("ok"))
.mountApp("/foo", innerApp);

const server = new FakeServer(await app.handler());

let res = await server.get("/foo");
let res = await server.get("/");
expect(await res.text()).toEqual("ok");

res = await server.get("/foo");
expect(await res.text()).toEqual("A");

res = await server.post("/foo");
Expand Down

0 comments on commit 03cdf62

Please sign in to comment.