perf: pre-compile middleware chains at build time (#3104)
Pre-compiles middleware chains once at startup instead of constructing them per-request. ## Changes - Replace `runMiddlewares(middlewares, ctx, onError)` (per-request) with `compileMiddlewares(middlewares, onError)` (once at startup) which returns a single `Middleware<State>` function - Router now stores a single compiled handler per method/route (`T | null`) instead of arrays (`T[]`) - The compiled chain passes `tail` (the original `ctx.next`) as a parameter to each step, avoiding the infinite recursion bug where a compiled tail reads an already-overwritten `ctx.next` — safe under concurrent requests - Lazy middleware resolution is preserved: a lazy middleware is resolved on first request and the resolved function replaces the lazy wrapper in the closure ## Benchmarks Synthetic benchmarks (10 middlewares, `deno bench`) show the per-request savings are small in isolation — middleware execution and async/await overhead dominate. The main value is architectural: building the chain once is correct and eliminates per-request allocations, which may compound under high concurrency. --------- Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Bartek Iwańczuk
Claude Opus 4.6
parent
dc2324807c
commit
4edfe2f5a4
@@ -2,11 +2,7 @@ import { trace } from "@opentelemetry/api";
|
||||
|
||||
import { DENO_DEPLOYMENT_ID } from "@fresh/build-id";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import {
|
||||
type MaybeLazyMiddleware,
|
||||
type Middleware,
|
||||
runMiddlewares,
|
||||
} from "./middlewares/mod.ts";
|
||||
import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts";
|
||||
import { Context } from "./context.ts";
|
||||
import { mergePath, type Method, UrlPatternRouter } from "./router.ts";
|
||||
import type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
||||
@@ -387,12 +383,13 @@ export class App<State> {
|
||||
}
|
||||
}
|
||||
|
||||
const router = new UrlPatternRouter<MaybeLazyMiddleware<State>>();
|
||||
const router = new UrlPatternRouter<Middleware<State>>();
|
||||
|
||||
const { rootMiddlewares } = applyCommands(
|
||||
const { rootHandler } = applyCommands(
|
||||
router,
|
||||
this.#commands,
|
||||
this.config.basePath,
|
||||
this.#onError,
|
||||
);
|
||||
|
||||
return async (
|
||||
@@ -405,7 +402,7 @@ export class App<State> {
|
||||
|
||||
const method = req.method.toUpperCase() as Method;
|
||||
const matched = router.match(method, url);
|
||||
let { params, pattern, handlers, methodMatch } = matched;
|
||||
let { params, pattern, item: handler, methodMatch } = matched;
|
||||
|
||||
const span = trace.getActiveSpan();
|
||||
if (span && pattern) {
|
||||
@@ -416,7 +413,7 @@ export class App<State> {
|
||||
let next: () => Promise<Response>;
|
||||
|
||||
if (pattern === null || !methodMatch) {
|
||||
handlers = rootMiddlewares;
|
||||
handler = rootHandler;
|
||||
}
|
||||
|
||||
if (matched.pattern !== null && !methodMatch) {
|
||||
@@ -442,9 +439,7 @@ export class App<State> {
|
||||
);
|
||||
|
||||
try {
|
||||
if (handlers.length === 0) return await next();
|
||||
|
||||
const result = await runMiddlewares(handlers, ctx, this.#onError);
|
||||
const result = await (handler !== null ? handler(ctx) : next());
|
||||
if (!(result instanceof Response)) {
|
||||
throw new Error(
|
||||
`Expected a "Response" instance to be returned, but got: ${result}`,
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { setAdditionalStyles } from "./context.ts";
|
||||
import { HttpError } from "./error.ts";
|
||||
import { isHandlerByMethod, type PageResponse } from "./handlers.ts";
|
||||
import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts";
|
||||
import {
|
||||
compileMiddlewares,
|
||||
type MaybeLazyMiddleware,
|
||||
type Middleware,
|
||||
} from "./middlewares/mod.ts";
|
||||
import { mergePath, type Method, type Router, toRoutePath } from "./router.ts";
|
||||
import {
|
||||
getOrCreateSegment,
|
||||
@@ -202,22 +206,25 @@ export type Command<State> =
|
||||
| FsRouteCommand<State>;
|
||||
|
||||
export function applyCommands<State>(
|
||||
router: Router<MaybeLazyMiddleware<State>>,
|
||||
router: Router<Middleware<State>>,
|
||||
commands: Command<State>[],
|
||||
basePath: string,
|
||||
): { rootMiddlewares: MaybeLazyMiddleware<State>[] } {
|
||||
onError?: (err: unknown) => void,
|
||||
): { rootHandler: Middleware<State> } {
|
||||
const root = newSegment<State>("", null);
|
||||
|
||||
applyCommandsInner(root, router, commands, basePath);
|
||||
applyCommandsInner(root, router, commands, basePath, onError);
|
||||
|
||||
return { rootMiddlewares: segmentToMiddlewares(root) };
|
||||
const rootMiddlewares = segmentToMiddlewares(root);
|
||||
return { rootHandler: compileMiddlewares(rootMiddlewares, onError) };
|
||||
}
|
||||
|
||||
function applyCommandsInner<State>(
|
||||
root: Segment<State>,
|
||||
router: Router<MaybeLazyMiddleware<State>>,
|
||||
router: Router<Middleware<State>>,
|
||||
commands: Command<State>[],
|
||||
basePath: string,
|
||||
onError?: (err: unknown) => void,
|
||||
) {
|
||||
for (let i = 0; i < commands.length; i++) {
|
||||
const cmd = commands[i];
|
||||
@@ -290,18 +297,19 @@ function applyCommandsInner<State>(
|
||||
return renderRoute(ctx, def);
|
||||
});
|
||||
|
||||
const compiled = compileMiddlewares(fns, onError);
|
||||
if (config === undefined || config.methods === "ALL") {
|
||||
router.add("GET", routePath, fns);
|
||||
router.add("DELETE", routePath, fns);
|
||||
router.add("HEAD", routePath, fns);
|
||||
router.add("OPTIONS", routePath, fns);
|
||||
router.add("PATCH", routePath, fns);
|
||||
router.add("POST", routePath, fns);
|
||||
router.add("PUT", routePath, fns);
|
||||
router.add("GET", routePath, compiled);
|
||||
router.add("DELETE", routePath, compiled);
|
||||
router.add("HEAD", routePath, compiled);
|
||||
router.add("OPTIONS", routePath, compiled);
|
||||
router.add("PATCH", routePath, compiled);
|
||||
router.add("POST", routePath, compiled);
|
||||
router.add("PUT", routePath, compiled);
|
||||
} else if (Array.isArray(config.methods)) {
|
||||
for (let i = 0; i < config.methods.length; i++) {
|
||||
const method = config.methods[i];
|
||||
router.add(method, routePath, fns);
|
||||
router.add(method, routePath, compiled);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -313,17 +321,18 @@ function applyCommandsInner<State>(
|
||||
false,
|
||||
));
|
||||
|
||||
const compiled = compileMiddlewares(fns, onError);
|
||||
if (typeof route.handler === "function") {
|
||||
router.add("GET", routePath, fns);
|
||||
router.add("DELETE", routePath, fns);
|
||||
router.add("HEAD", routePath, fns);
|
||||
router.add("OPTIONS", routePath, fns);
|
||||
router.add("PATCH", routePath, fns);
|
||||
router.add("POST", routePath, fns);
|
||||
router.add("PUT", routePath, fns);
|
||||
router.add("GET", routePath, compiled);
|
||||
router.add("DELETE", routePath, compiled);
|
||||
router.add("HEAD", routePath, compiled);
|
||||
router.add("OPTIONS", routePath, compiled);
|
||||
router.add("PATCH", routePath, compiled);
|
||||
router.add("POST", routePath, compiled);
|
||||
router.add("PUT", routePath, compiled);
|
||||
} else if (isHandlerByMethod(route.handler!)) {
|
||||
for (const method of Object.keys(route.handler)) {
|
||||
router.add(method as Method, routePath, fns);
|
||||
router.add(method as Method, routePath, compiled);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -340,17 +349,18 @@ function applyCommandsInner<State>(
|
||||
|
||||
result.push(...fns);
|
||||
|
||||
const compiled = compileMiddlewares(result, onError);
|
||||
const resPath = toRoutePath(mergePath(basePath, pattern, false));
|
||||
if (method === "ALL") {
|
||||
router.add("GET", resPath, result);
|
||||
router.add("DELETE", resPath, result);
|
||||
router.add("HEAD", resPath, result);
|
||||
router.add("OPTIONS", resPath, result);
|
||||
router.add("PATCH", resPath, result);
|
||||
router.add("POST", resPath, result);
|
||||
router.add("PUT", resPath, result);
|
||||
router.add("GET", resPath, compiled);
|
||||
router.add("DELETE", resPath, compiled);
|
||||
router.add("HEAD", resPath, compiled);
|
||||
router.add("OPTIONS", resPath, compiled);
|
||||
router.add("PATCH", resPath, compiled);
|
||||
router.add("POST", resPath, compiled);
|
||||
router.add("PUT", resPath, compiled);
|
||||
} else {
|
||||
router.add(method, resPath, result);
|
||||
router.add(method, resPath, compiled);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -358,7 +368,7 @@ function applyCommandsInner<State>(
|
||||
case CommandType.FsRoute: {
|
||||
const items = cmd.getItems();
|
||||
const base = mergePath(basePath, cmd.pattern, true);
|
||||
applyCommandsInner(root, router, items, base);
|
||||
applyCommandsInner(root, router, items, base, onError);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
|
||||
@@ -88,56 +88,69 @@ export type MaybeLazyMiddleware<State> = (
|
||||
ctx: Context<State>,
|
||||
) => Response | Promise<Response | Middleware<State>>;
|
||||
|
||||
export async function runMiddlewares<State>(
|
||||
export function compileMiddlewares<State>(
|
||||
middlewares: MaybeLazyMiddleware<State>[],
|
||||
ctx: Context<State>,
|
||||
onError?: (err: unknown) => void,
|
||||
): Promise<Response> {
|
||||
return await tracer.startActiveSpan("middlewares", {
|
||||
attributes: { "fresh.middleware.count": middlewares.length },
|
||||
}, async (span) => {
|
||||
try {
|
||||
let fn = ctx.next;
|
||||
let i = middlewares.length;
|
||||
while (i--) {
|
||||
const local = fn;
|
||||
let next = middlewares[i];
|
||||
const idx = i;
|
||||
fn = async () => {
|
||||
const internals = getInternals(ctx);
|
||||
const { app: prevApp, layouts: prevLayouts } = internals;
|
||||
): Middleware<State> {
|
||||
if (middlewares.length === 0) return (ctx) => ctx.next();
|
||||
|
||||
ctx.next = local;
|
||||
try {
|
||||
const result = await next(ctx);
|
||||
if (typeof result === "function") {
|
||||
middlewares[idx] = result;
|
||||
next = result;
|
||||
return await result(ctx);
|
||||
}
|
||||
// Each step is a function that takes (ctx, tail) where tail is the
|
||||
// original ctx.next captured at invocation time. This avoids the
|
||||
// infinite recursion bug where the compiled tail reads an already-
|
||||
// overwritten ctx.next, and is safe under concurrent requests.
|
||||
type ChainFn = (
|
||||
ctx: Context<State>,
|
||||
tail: () => Promise<Response>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
if (ctx.error !== err) {
|
||||
ctx.error = err;
|
||||
let chain: ChainFn = (_ctx, tail) => tail();
|
||||
|
||||
if (onError !== undefined) {
|
||||
onError(err);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
internals.app = prevApp;
|
||||
internals.layouts = prevLayouts;
|
||||
for (let i = middlewares.length - 1; i >= 0; i--) {
|
||||
const nextChain = chain;
|
||||
let middleware = middlewares[i];
|
||||
chain = async (ctx, tail) => {
|
||||
const internals = getInternals(ctx);
|
||||
const { app: prevApp, layouts: prevLayouts } = internals;
|
||||
|
||||
ctx.next = () => Promise.resolve(nextChain(ctx, tail));
|
||||
try {
|
||||
const result = await middleware(ctx);
|
||||
if (typeof result === "function") {
|
||||
middleware = result;
|
||||
return await result(ctx);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
if (ctx.error !== err) {
|
||||
ctx.error = err;
|
||||
|
||||
if (onError !== undefined) {
|
||||
onError(err);
|
||||
}
|
||||
};
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
internals.app = prevApp;
|
||||
internals.layouts = prevLayouts;
|
||||
}
|
||||
return await fn();
|
||||
} catch (err) {
|
||||
recordSpanError(span, err);
|
||||
throw err;
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const count = middlewares.length;
|
||||
return (ctx) => {
|
||||
const tail = ctx.next;
|
||||
return tracer.startActiveSpan("middlewares", {
|
||||
attributes: { "fresh.middleware.count": count },
|
||||
}, async (span) => {
|
||||
try {
|
||||
return await chain(ctx, tail);
|
||||
} catch (err) {
|
||||
recordSpanError(span, err);
|
||||
throw err;
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { runMiddlewares } from "./mod.ts";
|
||||
import { compileMiddlewares } from "./mod.ts";
|
||||
import { expect } from "@std/expect";
|
||||
import { serveMiddleware } from "../test_utils.ts";
|
||||
import type { Middleware } from "./mod.ts";
|
||||
import type { Lazy, MaybeLazy } from "../types.ts";
|
||||
|
||||
Deno.test("runMiddleware", async () => {
|
||||
Deno.test("compileMiddlewares", async () => {
|
||||
const middlewares: Middleware<{ text: string }>[] = [
|
||||
(ctx) => {
|
||||
ctx.state.text = "A";
|
||||
@@ -24,15 +24,15 @@ Deno.test("runMiddleware", async () => {
|
||||
},
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||
runMiddlewares(middlewares, ctx)
|
||||
const server = serveMiddleware<{ text: string }>(
|
||||
compileMiddlewares(middlewares),
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("AB");
|
||||
});
|
||||
|
||||
Deno.test("runMiddleware - middlewares should only be called once", async () => {
|
||||
Deno.test("compileMiddlewares - middlewares should only be called once", async () => {
|
||||
const A: Middleware<{ count: number }> = (ctx) => {
|
||||
if (ctx.state.count === undefined) {
|
||||
ctx.state.count = 0;
|
||||
@@ -42,21 +42,21 @@ Deno.test("runMiddleware - middlewares should only be called once", async () =>
|
||||
return ctx.next();
|
||||
};
|
||||
|
||||
const server = serveMiddleware<{ count: number }>((ctx) =>
|
||||
runMiddlewares(
|
||||
[A, (ctx) => new Response(String(ctx.state.count))],
|
||||
ctx,
|
||||
)
|
||||
const final: Middleware<{ count: number }> = (ctx) =>
|
||||
new Response(String(ctx.state.count));
|
||||
|
||||
const server = serveMiddleware<{ count: number }>(
|
||||
compileMiddlewares([A, final]),
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("0");
|
||||
});
|
||||
|
||||
Deno.test("runMiddleware - runs multiple stacks", async () => {
|
||||
Deno.test("compileMiddlewares - runs multiple stacks", async () => {
|
||||
type State = { text: string };
|
||||
const A: Middleware<State> = (ctx) => {
|
||||
ctx.state.text += "A";
|
||||
ctx.state.text = "A";
|
||||
return ctx.next();
|
||||
};
|
||||
const B: Middleware<State> = (ctx) => {
|
||||
@@ -72,25 +72,18 @@ Deno.test("runMiddleware - runs multiple stacks", async () => {
|
||||
return ctx.next();
|
||||
};
|
||||
|
||||
const server = serveMiddleware<State>((ctx) => {
|
||||
ctx.state.text = "";
|
||||
return runMiddlewares(
|
||||
[
|
||||
A,
|
||||
B,
|
||||
C,
|
||||
D,
|
||||
(ctx) => new Response(String(ctx.state.text)),
|
||||
],
|
||||
ctx,
|
||||
);
|
||||
});
|
||||
const final: Middleware<State> = (ctx) =>
|
||||
new Response(String(ctx.state.text));
|
||||
|
||||
const server = serveMiddleware<State>(
|
||||
compileMiddlewares([A, B, C, D, final]),
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("ABCD");
|
||||
});
|
||||
|
||||
Deno.test("runMiddleware - throws errors", async () => {
|
||||
Deno.test("compileMiddlewares - throws errors", async () => {
|
||||
let thrownA: unknown = null;
|
||||
let thrownB: unknown = null;
|
||||
let thrownC: unknown = null;
|
||||
@@ -125,8 +118,8 @@ Deno.test("runMiddleware - throws errors", async () => {
|
||||
},
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||
runMiddlewares(middlewares, ctx)
|
||||
const server = serveMiddleware<{ text: string }>(
|
||||
compileMiddlewares(middlewares),
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -139,7 +132,7 @@ Deno.test("runMiddleware - throws errors", async () => {
|
||||
expect(thrownC).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
Deno.test("runMiddleware - lazy middlewares", async () => {
|
||||
Deno.test("compileMiddlewares - lazy middlewares", async () => {
|
||||
type State = { text: string };
|
||||
|
||||
let called = 0;
|
||||
@@ -164,9 +157,8 @@ Deno.test("runMiddleware - lazy middlewares", async () => {
|
||||
},
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>((ctx) =>
|
||||
runMiddlewares(middlewares, ctx)
|
||||
);
|
||||
const compiled = compileMiddlewares(middlewares);
|
||||
const server = serveMiddleware<{ text: string }>(compiled);
|
||||
|
||||
let res = await server.get("/");
|
||||
expect(await res.text()).toEqual("A_lazy_B");
|
||||
@@ -177,3 +169,112 @@ Deno.test("runMiddleware - lazy middlewares", async () => {
|
||||
expect(await res.text()).toEqual("A_lazy_B");
|
||||
expect(called).toEqual(1);
|
||||
});
|
||||
|
||||
Deno.test("compileMiddlewares - single middleware", async () => {
|
||||
const server = serveMiddleware<{ text: string }>(
|
||||
compileMiddlewares([() => new Response("single")]),
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("single");
|
||||
});
|
||||
|
||||
Deno.test("compileMiddlewares - post-processing after next()", async () => {
|
||||
type State = { text: string };
|
||||
|
||||
const middlewares: Middleware<State>[] = [
|
||||
async (ctx) => {
|
||||
const res = await ctx.next();
|
||||
const text = await res.text();
|
||||
return new Response(`wrapped(${text})`);
|
||||
},
|
||||
() => new Response("inner"),
|
||||
];
|
||||
|
||||
const server = serveMiddleware<State>(
|
||||
compileMiddlewares(middlewares),
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("wrapped(inner)");
|
||||
});
|
||||
|
||||
Deno.test("compileMiddlewares - concurrent requests share compiled chain", async () => {
|
||||
type State = { text: string };
|
||||
let concurrency = 0;
|
||||
let maxConcurrency = 0;
|
||||
|
||||
const middlewares: Middleware<State>[] = [
|
||||
async (ctx) => {
|
||||
concurrency++;
|
||||
if (concurrency > maxConcurrency) maxConcurrency = concurrency;
|
||||
// Yield to let other requests enter the middleware
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
const res = await ctx.next();
|
||||
concurrency--;
|
||||
return res;
|
||||
},
|
||||
(ctx) => new Response(ctx.url.pathname),
|
||||
];
|
||||
|
||||
const compiled = compileMiddlewares(middlewares);
|
||||
const server = serveMiddleware<State>(compiled);
|
||||
|
||||
// Fire concurrent requests
|
||||
const results = await Promise.all([
|
||||
server.get("/a").then((r) => r.text()),
|
||||
server.get("/b").then((r) => r.text()),
|
||||
server.get("/c").then((r) => r.text()),
|
||||
]);
|
||||
|
||||
expect(results).toEqual(["/a", "/b", "/c"]);
|
||||
expect(maxConcurrency).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
Deno.test("compileMiddlewares - onError callback", async () => {
|
||||
const errors: unknown[] = [];
|
||||
const middlewares: Middleware<{ text: string }>[] = [
|
||||
() => {
|
||||
throw new Error("test error");
|
||||
},
|
||||
];
|
||||
|
||||
const server = serveMiddleware<{ text: string }>(
|
||||
compileMiddlewares(middlewares, (err) => errors.push(err)),
|
||||
);
|
||||
|
||||
try {
|
||||
await server.get("/");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
expect(errors.length).toEqual(1);
|
||||
expect(errors[0]).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
Deno.test("compileMiddlewares - empty array falls through to next", async () => {
|
||||
const server = serveMiddleware<{ text: string }>(
|
||||
compileMiddlewares([]),
|
||||
{ next: () => Promise.resolve(new Response("fallthrough")) },
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("fallthrough");
|
||||
});
|
||||
|
||||
Deno.test("compileMiddlewares - calls last next", async () => {
|
||||
const middlewares: Middleware<{ text: string }>[] = [
|
||||
(ctx) => ctx.next(),
|
||||
];
|
||||
|
||||
const next = () => Promise.resolve(new Response("next"));
|
||||
|
||||
const server = serveMiddleware<{ text: string }>(
|
||||
compileMiddlewares(middlewares),
|
||||
{ next },
|
||||
);
|
||||
|
||||
const res = await server.get("/");
|
||||
expect(await res.text()).toEqual("next");
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ export type Method =
|
||||
| "OPTIONS";
|
||||
|
||||
export type RouteByMethod<T> = {
|
||||
[m in Method]: T[];
|
||||
[m in Method]: T | null;
|
||||
};
|
||||
|
||||
export interface StaticRouteDef<T> {
|
||||
@@ -23,30 +23,30 @@ export interface DynamicRouteDef<T> {
|
||||
|
||||
function newByMethod<T>(): RouteByMethod<T> {
|
||||
return {
|
||||
GET: [],
|
||||
POST: [],
|
||||
PATCH: [],
|
||||
DELETE: [],
|
||||
PUT: [],
|
||||
HEAD: [],
|
||||
OPTIONS: [],
|
||||
GET: null,
|
||||
POST: null,
|
||||
PATCH: null,
|
||||
DELETE: null,
|
||||
PUT: null,
|
||||
HEAD: null,
|
||||
OPTIONS: null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface RouteResult<T> {
|
||||
params: Record<string, string>;
|
||||
handlers: T[];
|
||||
item: T | null;
|
||||
methodMatch: boolean;
|
||||
pattern: string | null;
|
||||
}
|
||||
|
||||
export interface Router<T> {
|
||||
add(
|
||||
method: Method | "ALL",
|
||||
method: Method,
|
||||
pathname: string,
|
||||
handlers: T[],
|
||||
item: T,
|
||||
): void;
|
||||
match(method: Method, url: URL, init?: T[]): RouteResult<T>;
|
||||
match(method: Method, url: URL): RouteResult<T>;
|
||||
getAllowedMethods(pattern: string): string[];
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ export class UrlPatternRouter<T> implements Router<T> {
|
||||
add(
|
||||
method: Method,
|
||||
pathname: string,
|
||||
handlers: T[],
|
||||
item: T,
|
||||
) {
|
||||
let allowed = this.#allowed.get(pathname);
|
||||
if (allowed === undefined) {
|
||||
@@ -105,13 +105,15 @@ export class UrlPatternRouter<T> implements Router<T> {
|
||||
byMethod = def.byMethod;
|
||||
}
|
||||
|
||||
byMethod[method].push(...handlers);
|
||||
if (byMethod[method] === null) {
|
||||
byMethod[method] = item;
|
||||
}
|
||||
}
|
||||
|
||||
match(method: Method, url: URL, init: T[] = []): RouteResult<T> {
|
||||
match(method: Method, url: URL): RouteResult<T> {
|
||||
const result: RouteResult<T> = {
|
||||
params: Object.create(null),
|
||||
handlers: init,
|
||||
item: null,
|
||||
methodMatch: false,
|
||||
pattern: null,
|
||||
};
|
||||
@@ -137,13 +139,13 @@ export class UrlPatternRouter<T> implements Router<T> {
|
||||
if (staticMatch !== undefined) {
|
||||
result.pattern = pathname;
|
||||
|
||||
let handlers = staticMatch.byMethod[method];
|
||||
if (method === "HEAD" && handlers.length === 0) {
|
||||
handlers = staticMatch.byMethod.GET;
|
||||
let item = staticMatch.byMethod[method];
|
||||
if (method === "HEAD" && item === null) {
|
||||
item = staticMatch.byMethod.GET;
|
||||
}
|
||||
if (handlers.length > 0) {
|
||||
if (item !== null) {
|
||||
result.methodMatch = true;
|
||||
result.handlers.push(...handlers);
|
||||
result.item = item;
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -157,14 +159,14 @@ export class UrlPatternRouter<T> implements Router<T> {
|
||||
|
||||
result.pattern = route.pattern.pathname;
|
||||
|
||||
let handlers = route.byMethod[method];
|
||||
if (method === "HEAD" && handlers.length === 0) {
|
||||
handlers = route.byMethod.GET;
|
||||
let item = route.byMethod[method];
|
||||
if (method === "HEAD" && item === null) {
|
||||
item = route.byMethod.GET;
|
||||
}
|
||||
|
||||
if (handlers.length > 0) {
|
||||
if (item !== null) {
|
||||
result.methodMatch = true;
|
||||
result.handlers.push(...handlers);
|
||||
result.item = item;
|
||||
|
||||
// Decode matched params
|
||||
for (const [key, value] of Object.entries(match.pathname.groups)) {
|
||||
|
||||
@@ -20,12 +20,12 @@ Deno.test("IS_PATTERN", () => {
|
||||
Deno.test("UrlPatternRouter - GET extract params", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/:foo/:bar/c", [A]);
|
||||
router.add("GET", "/:foo/:bar/c", A);
|
||||
|
||||
let res = router.match("GET", new URL("/a/b/c", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: { foo: "a", bar: "b" },
|
||||
handlers: [A],
|
||||
item: A,
|
||||
methodMatch: true,
|
||||
pattern: "/:foo/:bar/c",
|
||||
});
|
||||
@@ -34,7 +34,7 @@ Deno.test("UrlPatternRouter - GET extract params", () => {
|
||||
res = router.match("GET", new URL("/a%20a/b/c", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: { foo: "a a", bar: "b" },
|
||||
handlers: [A],
|
||||
item: A,
|
||||
methodMatch: true,
|
||||
pattern: "/:foo/:bar/c",
|
||||
});
|
||||
@@ -43,12 +43,12 @@ Deno.test("UrlPatternRouter - GET extract params", () => {
|
||||
Deno.test("UrlPatternRouter - Wrong method match", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/foo", [A]);
|
||||
router.add("GET", "/foo", A);
|
||||
|
||||
const res = router.match("POST", new URL("/foo", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [],
|
||||
item: null,
|
||||
methodMatch: false,
|
||||
pattern: "/foo",
|
||||
});
|
||||
@@ -58,13 +58,13 @@ Deno.test("UrlPatternRouter - wrong + correct method", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
const B = () => {};
|
||||
router.add("GET", "/foo", [A]);
|
||||
router.add("POST", "/foo", [B]);
|
||||
router.add("GET", "/foo", A);
|
||||
router.add("POST", "/foo", B);
|
||||
|
||||
const res = router.match("POST", new URL("/foo", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [B],
|
||||
item: B,
|
||||
methodMatch: true,
|
||||
pattern: "/foo",
|
||||
});
|
||||
@@ -73,12 +73,12 @@ Deno.test("UrlPatternRouter - wrong + correct method", () => {
|
||||
Deno.test("UrlPatternRouter - trailing slash matches route without slash", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/wissen", [A]);
|
||||
router.add("GET", "/wissen", A);
|
||||
|
||||
const res = router.match("GET", new URL("/wissen/", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [A],
|
||||
item: A,
|
||||
methodMatch: true,
|
||||
pattern: "/wissen",
|
||||
});
|
||||
@@ -87,12 +87,12 @@ Deno.test("UrlPatternRouter - trailing slash matches route without slash", () =>
|
||||
Deno.test("UrlPatternRouter - no trailing slash matches route with slash", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/wissen/", [A]);
|
||||
router.add("GET", "/wissen/", A);
|
||||
|
||||
const res = router.match("GET", new URL("/wissen", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [A],
|
||||
item: A,
|
||||
methodMatch: true,
|
||||
pattern: "/wissen/",
|
||||
});
|
||||
@@ -102,8 +102,8 @@ Deno.test("UrlPatternRouter - exact match takes priority over trailing slash fal
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
const B = () => {};
|
||||
router.add("GET", "/wissen", [A]);
|
||||
router.add("GET", "/wissen/", [B]);
|
||||
router.add("GET", "/wissen", A);
|
||||
router.add("GET", "/wissen/", B);
|
||||
|
||||
const withSlash = router.match(
|
||||
"GET",
|
||||
@@ -111,7 +111,7 @@ Deno.test("UrlPatternRouter - exact match takes priority over trailing slash fal
|
||||
);
|
||||
expect(withSlash).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [B],
|
||||
item: B,
|
||||
methodMatch: true,
|
||||
pattern: "/wissen/",
|
||||
});
|
||||
@@ -122,7 +122,7 @@ Deno.test("UrlPatternRouter - exact match takes priority over trailing slash fal
|
||||
);
|
||||
expect(withoutSlash).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [A],
|
||||
item: A,
|
||||
methodMatch: true,
|
||||
pattern: "/wissen",
|
||||
});
|
||||
@@ -131,12 +131,12 @@ Deno.test("UrlPatternRouter - exact match takes priority over trailing slash fal
|
||||
Deno.test("UrlPatternRouter - root trailing slash does not double-match", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/", [A]);
|
||||
router.add("GET", "/", A);
|
||||
|
||||
const res = router.match("GET", new URL("/", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: Object.create(null),
|
||||
handlers: [A],
|
||||
item: A,
|
||||
methodMatch: true,
|
||||
pattern: "/",
|
||||
});
|
||||
@@ -145,14 +145,14 @@ Deno.test("UrlPatternRouter - root trailing slash does not double-match", () =>
|
||||
Deno.test("UrlPatternRouter - convert patterns automatically", () => {
|
||||
const router = new UrlPatternRouter();
|
||||
const A = () => {};
|
||||
router.add("GET", "/books/:id", [A]);
|
||||
router.add("GET", "/books/:id", A);
|
||||
|
||||
const res = router.match("GET", new URL("/books/foo", "http://localhost"));
|
||||
expect(res).toEqual({
|
||||
params: {
|
||||
id: "foo",
|
||||
},
|
||||
handlers: [A],
|
||||
item: A,
|
||||
methodMatch: true,
|
||||
pattern: "/books/:id",
|
||||
});
|
||||
@@ -259,3 +259,30 @@ Deno.test("mergePath", () => {
|
||||
expect(mergePath("/foo", "*", true)).toEqual("/foo");
|
||||
expect(mergePath("/foo", "/*", true)).toEqual("/foo/*");
|
||||
});
|
||||
|
||||
Deno.test("UrlPatternRouter - first registered route wins on duplicate", () => {
|
||||
const router = new UrlPatternRouter<() => string>();
|
||||
const first = () => "first";
|
||||
const second = () => "second";
|
||||
|
||||
router.add("GET", "/foo", first);
|
||||
router.add("GET", "/foo", second);
|
||||
|
||||
const res = router.match("GET", new URL("/foo", "http://localhost"));
|
||||
expect(res.item).toBe(first);
|
||||
});
|
||||
|
||||
Deno.test("UrlPatternRouter - duplicate registration different methods", () => {
|
||||
const router = new UrlPatternRouter<() => string>();
|
||||
const getHandler = () => "get";
|
||||
const postHandler = () => "post";
|
||||
|
||||
router.add("GET", "/foo", getHandler);
|
||||
router.add("POST", "/foo", postHandler);
|
||||
|
||||
const getRes = router.match("GET", new URL("/foo", "http://localhost"));
|
||||
expect(getRes.item).toBe(getHandler);
|
||||
|
||||
const postRes = router.match("POST", new URL("/foo", "http://localhost"));
|
||||
expect(postRes.item).toBe(postHandler);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user