feat(server): middleware params (#1314)
This commit is contained in:
@@ -98,6 +98,23 @@ export const handler = [
|
||||
];
|
||||
```
|
||||
|
||||
It should be noted that `middleware` has access to route parameters. If you're
|
||||
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
||||
|
||||
```ts
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||
const currentTenant = ctx.params.tenant;
|
||||
//do something with the tenant
|
||||
const resp = await ctx.next();
|
||||
return resp;
|
||||
}
|
||||
```
|
||||
|
||||
and the request is to `mysaas.com/acme/admin/`, then `currentTenant` will have
|
||||
the value of `acme` in your middleware.
|
||||
|
||||
## Middleware Destination
|
||||
|
||||
To set the stage for this section, `MiddlewareHandlerContext` looks like this:
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
EsbuildBuilder,
|
||||
JSXConfig,
|
||||
} from "../build/mod.ts";
|
||||
import { InternalRoute } from "./router.ts";
|
||||
|
||||
const DEFAULT_CONN_INFO: ConnInfo = {
|
||||
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
||||
@@ -379,6 +380,7 @@ export class ServerContext {
|
||||
const withMiddlewares = this.#composeMiddlewares(
|
||||
this.#middlewares,
|
||||
handlers.errorHandler,
|
||||
router.getParamsAndRoute<RouterState>(handlers),
|
||||
);
|
||||
const trailingSlashEnabled = this.#routerOptions?.trailingSlash;
|
||||
return async function handler(
|
||||
@@ -437,6 +439,12 @@ export class ServerContext {
|
||||
#composeMiddlewares(
|
||||
middlewares: MiddlewareRoute[],
|
||||
errorHandler: router.ErrorHandler<RouterState>,
|
||||
paramsAndRoute: (
|
||||
url: string,
|
||||
) => {
|
||||
route: InternalRoute<RouterState> | undefined;
|
||||
params: Record<string, string>;
|
||||
},
|
||||
) {
|
||||
return (
|
||||
req: Request,
|
||||
@@ -448,6 +456,7 @@ export class ServerContext {
|
||||
const mws = selectMiddlewares(req.url, middlewares);
|
||||
|
||||
const handlers: (() => Response | Promise<Response>)[] = [];
|
||||
const paramsAndRouteResult = paramsAndRoute(req.url);
|
||||
|
||||
const middlewareCtx: MiddlewareHandlerContext = {
|
||||
next() {
|
||||
@@ -470,6 +479,7 @@ export class ServerContext {
|
||||
...connInfo,
|
||||
state: {},
|
||||
destination: "route",
|
||||
params: paramsAndRouteResult.params,
|
||||
};
|
||||
|
||||
for (const mw of mws) {
|
||||
@@ -490,6 +500,8 @@ export class ServerContext {
|
||||
const { destination, handler } = inner(
|
||||
req,
|
||||
ctx,
|
||||
paramsAndRouteResult.params,
|
||||
paramsAndRouteResult.route,
|
||||
);
|
||||
handlers.push(handler);
|
||||
middlewareCtx.destination = destination;
|
||||
|
||||
+30
-9
@@ -10,6 +10,8 @@ export type Handler<T = unknown> = (
|
||||
export type FinalHandler<T = unknown> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
params: Record<string, string>,
|
||||
route?: InternalRoute<T>,
|
||||
) => {
|
||||
destination: DestinationKind;
|
||||
handler: () => Response | Promise<Response>;
|
||||
@@ -125,25 +127,22 @@ function processRoutes<T>(
|
||||
}
|
||||
}
|
||||
|
||||
export function router<T = unknown>(
|
||||
export function getParamsAndRoute<T>(
|
||||
{
|
||||
internalRoutes,
|
||||
staticRoutes,
|
||||
routes,
|
||||
otherHandler,
|
||||
unknownMethodHandler,
|
||||
}: RouterOptions<T>,
|
||||
): FinalHandler<T> {
|
||||
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
||||
|
||||
): (
|
||||
url: string,
|
||||
) => { route: InternalRoute<T> | undefined; params: Record<string, string> } {
|
||||
const processedRoutes: InternalRoute<T>[] = [];
|
||||
processRoutes(processedRoutes, internalRoutes, "internal");
|
||||
processRoutes(processedRoutes, staticRoutes, "static");
|
||||
processRoutes(processedRoutes, routes, "route");
|
||||
|
||||
return (req, ctx) => {
|
||||
return (url: string) => {
|
||||
for (const route of processedRoutes) {
|
||||
const res = route.pattern.exec(req.url);
|
||||
const res = route.pattern.exec(url);
|
||||
|
||||
if (res !== null) {
|
||||
const groups: Record<string, string> = {};
|
||||
@@ -156,7 +155,29 @@ export function router<T = unknown>(
|
||||
groups[key] = decodeURIComponent(value);
|
||||
}
|
||||
}
|
||||
return { route: route, params: groups };
|
||||
}
|
||||
}
|
||||
return {
|
||||
route: undefined,
|
||||
params: {},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export function router<T = unknown>(
|
||||
{
|
||||
otherHandler,
|
||||
unknownMethodHandler,
|
||||
}: RouterOptions<T>,
|
||||
): FinalHandler<T> {
|
||||
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
||||
|
||||
return (req, ctx, groups, route) => {
|
||||
if (route) {
|
||||
const res = route.pattern.exec(req.url);
|
||||
|
||||
if (res !== null) {
|
||||
// If not overridden, HEAD requests should be handled as GET requests but without the body.
|
||||
if (req.method === "HEAD" && !route.methods["HEAD"]) {
|
||||
req = new Request(req.url, { method: "GET", headers: req.headers });
|
||||
|
||||
@@ -231,6 +231,7 @@ export interface MiddlewareHandlerContext<State = Record<string, unknown>>
|
||||
next: () => Promise<Response>;
|
||||
state: State;
|
||||
destination: router.DestinationKind;
|
||||
params: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface MiddlewareRoute extends Middleware {
|
||||
|
||||
+36
-30
@@ -25,21 +25,24 @@ import * as $19 from "./routes/islands/root_fragment.tsx";
|
||||
import * as $20 from "./routes/islands/root_fragment_conditional_first.tsx";
|
||||
import * as $21 from "./routes/layeredMdw/_middleware.ts";
|
||||
import * as $22 from "./routes/layeredMdw/layer2-no-mw/without_mw.ts";
|
||||
import * as $23 from "./routes/layeredMdw/layer2/_middleware.ts";
|
||||
import * as $24 from "./routes/layeredMdw/layer2/abc.ts";
|
||||
import * as $25 from "./routes/layeredMdw/layer2/index.ts";
|
||||
import * as $26 from "./routes/layeredMdw/layer2/layer3/[id].ts";
|
||||
import * as $27 from "./routes/layeredMdw/layer2/layer3/_middleware.ts";
|
||||
import * as $28 from "./routes/middleware_root.ts";
|
||||
import * as $29 from "./routes/not_found.ts";
|
||||
import * as $30 from "./routes/params.tsx";
|
||||
import * as $31 from "./routes/props/[id].tsx";
|
||||
import * as $32 from "./routes/state-in-props/_middleware.ts";
|
||||
import * as $33 from "./routes/state-in-props/index.tsx";
|
||||
import * as $34 from "./routes/static.tsx";
|
||||
import * as $35 from "./routes/status_overwrite.tsx";
|
||||
import * as $36 from "./routes/umlaut-äöüß.tsx";
|
||||
import * as $37 from "./routes/wildcard.tsx";
|
||||
import * as $23 from "./routes/layeredMdw/layer2-with-params/[tenantId]/[id].ts";
|
||||
import * as $24 from "./routes/layeredMdw/layer2-with-params/[tenantId]/_middleware.ts";
|
||||
import * as $25 from "./routes/layeredMdw/layer2-with-params/_middleware.ts";
|
||||
import * as $26 from "./routes/layeredMdw/layer2/_middleware.ts";
|
||||
import * as $27 from "./routes/layeredMdw/layer2/abc.ts";
|
||||
import * as $28 from "./routes/layeredMdw/layer2/index.ts";
|
||||
import * as $29 from "./routes/layeredMdw/layer2/layer3/[id].ts";
|
||||
import * as $30 from "./routes/layeredMdw/layer2/layer3/_middleware.ts";
|
||||
import * as $31 from "./routes/middleware_root.ts";
|
||||
import * as $32 from "./routes/not_found.ts";
|
||||
import * as $33 from "./routes/params.tsx";
|
||||
import * as $34 from "./routes/props/[id].tsx";
|
||||
import * as $35 from "./routes/state-in-props/_middleware.ts";
|
||||
import * as $36 from "./routes/state-in-props/index.tsx";
|
||||
import * as $37 from "./routes/static.tsx";
|
||||
import * as $38 from "./routes/status_overwrite.tsx";
|
||||
import * as $39 from "./routes/umlaut-äöüß.tsx";
|
||||
import * as $40 from "./routes/wildcard.tsx";
|
||||
import * as $$0 from "./islands/Counter.tsx";
|
||||
import * as $$1 from "./islands/MultipleCounters.tsx";
|
||||
import * as $$2 from "./islands/ReturningNull.tsx";
|
||||
@@ -75,21 +78,24 @@ const manifest = {
|
||||
"./routes/islands/root_fragment_conditional_first.tsx": $20,
|
||||
"./routes/layeredMdw/_middleware.ts": $21,
|
||||
"./routes/layeredMdw/layer2-no-mw/without_mw.ts": $22,
|
||||
"./routes/layeredMdw/layer2/_middleware.ts": $23,
|
||||
"./routes/layeredMdw/layer2/abc.ts": $24,
|
||||
"./routes/layeredMdw/layer2/index.ts": $25,
|
||||
"./routes/layeredMdw/layer2/layer3/[id].ts": $26,
|
||||
"./routes/layeredMdw/layer2/layer3/_middleware.ts": $27,
|
||||
"./routes/middleware_root.ts": $28,
|
||||
"./routes/not_found.ts": $29,
|
||||
"./routes/params.tsx": $30,
|
||||
"./routes/props/[id].tsx": $31,
|
||||
"./routes/state-in-props/_middleware.ts": $32,
|
||||
"./routes/state-in-props/index.tsx": $33,
|
||||
"./routes/static.tsx": $34,
|
||||
"./routes/status_overwrite.tsx": $35,
|
||||
"./routes/umlaut-äöüß.tsx": $36,
|
||||
"./routes/wildcard.tsx": $37,
|
||||
"./routes/layeredMdw/layer2-with-params/[tenantId]/[id].ts": $23,
|
||||
"./routes/layeredMdw/layer2-with-params/[tenantId]/_middleware.ts": $24,
|
||||
"./routes/layeredMdw/layer2-with-params/_middleware.ts": $25,
|
||||
"./routes/layeredMdw/layer2/_middleware.ts": $26,
|
||||
"./routes/layeredMdw/layer2/abc.ts": $27,
|
||||
"./routes/layeredMdw/layer2/index.ts": $28,
|
||||
"./routes/layeredMdw/layer2/layer3/[id].ts": $29,
|
||||
"./routes/layeredMdw/layer2/layer3/_middleware.ts": $30,
|
||||
"./routes/middleware_root.ts": $31,
|
||||
"./routes/not_found.ts": $32,
|
||||
"./routes/params.tsx": $33,
|
||||
"./routes/props/[id].tsx": $34,
|
||||
"./routes/state-in-props/_middleware.ts": $35,
|
||||
"./routes/state-in-props/index.tsx": $36,
|
||||
"./routes/static.tsx": $37,
|
||||
"./routes/status_overwrite.tsx": $38,
|
||||
"./routes/umlaut-äöüß.tsx": $39,
|
||||
"./routes/wildcard.tsx": $40,
|
||||
},
|
||||
islands: {
|
||||
"./islands/Counter.tsx": $$0,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers<undefined> = {
|
||||
GET(_req: Request, _ctx) {
|
||||
return new Response(JSON.stringify({}));
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||
const resp = await ctx.next();
|
||||
resp.headers.set("middlewareParams_inner", JSON.stringify(ctx.params));
|
||||
return resp;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||
|
||||
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||
const resp = await ctx.next();
|
||||
resp.headers.set("middlewareParams_outer", JSON.stringify(ctx.params));
|
||||
return resp;
|
||||
}
|
||||
@@ -568,6 +568,31 @@ Deno.test({
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "/middleware - middlewareParams",
|
||||
fn: async () => {
|
||||
const resp = await handler(
|
||||
new Request(
|
||||
"https://fresh.deno.dev/layeredMdw/layer2-with-params/tenant1/resource1",
|
||||
),
|
||||
);
|
||||
assert(resp);
|
||||
assertEquals(resp.status, Status.OK);
|
||||
const _body = await resp.text();
|
||||
// assert that outer has access to all params
|
||||
assertEquals(
|
||||
resp.headers.get("middlewareParams_outer"),
|
||||
JSON.stringify({ tenantId: "tenant1", id: "resource1" }),
|
||||
);
|
||||
// assert that inner also has access to all params
|
||||
assertEquals(
|
||||
resp.headers.get("middlewareParams_inner"),
|
||||
JSON.stringify({ tenantId: "tenant1", id: "resource1" }),
|
||||
);
|
||||
assertEquals(resp.headers.get("server"), "fresh test server");
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "/not_found",
|
||||
fn: async () => {
|
||||
|
||||
Reference in New Issue
Block a user