fix: middleware not matching routes with optional parameters in fs routing (#3726)
Closes #3545 Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
ad8ec0fa42
commit
9e7adc084b
@@ -288,21 +288,27 @@ export function patternToSegments(
|
||||
|
||||
if (path === "/" || path === "*" || path === "/*") return out;
|
||||
|
||||
// Strip optional groups like {/:param}? before segmenting, so that
|
||||
// /api{/:opt}?/endpoint produces the same segments as /api/endpoint.
|
||||
// This ensures middleware registered at /api applies to routes with
|
||||
// optional parameters under /api.
|
||||
const cleaned = path.replace(/\{[^}]*\}\??/g, "");
|
||||
|
||||
let start = -1;
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
const ch = path[i];
|
||||
for (let i = 0; i < cleaned.length; i++) {
|
||||
const ch = cleaned[i];
|
||||
|
||||
if (ch === "/") {
|
||||
if (i > 0) {
|
||||
const raw = path.slice(start + 1, i);
|
||||
const raw = cleaned.slice(start + 1, i);
|
||||
out.push(raw);
|
||||
}
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
|
||||
if (includeLast && start < path.length - 1) {
|
||||
out.push(path.slice(start + 1));
|
||||
if (includeLast && start < cleaned.length - 1) {
|
||||
out.push(cleaned.slice(start + 1));
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
@@ -224,6 +224,14 @@ Deno.test("patternToSegments", () => {
|
||||
expect(patternToSegments("/foo/", "")).toEqual(["", "foo"]);
|
||||
|
||||
expect(patternToSegments("/foo/bar", "", true)).toEqual(["", "foo", "bar"]);
|
||||
|
||||
// Optional params with {/...}? syntax should not split on / inside braces
|
||||
expect(patternToSegments("/api{/:opt}?/endpoint", "")).toEqual(["", "api"]);
|
||||
expect(patternToSegments("/api{/:opt}?/endpoint", "", true)).toEqual([
|
||||
"",
|
||||
"api",
|
||||
"endpoint",
|
||||
]);
|
||||
});
|
||||
|
||||
Deno.test("mergePath", () => {
|
||||
|
||||
Reference in New Issue
Block a user