Skip to content

Commit

Permalink
Fix optional parameter matching
Browse files Browse the repository at this point in the history
  • Loading branch information
neemzy committed Oct 6, 2023
1 parent f77743a commit cb83034
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/real-cups-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@remix-run/router": patch
---

Fix optional parameter matching
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@
- morleytatro
- ms10596
- ned-park
- neemzy
- nilubisan
- Nismit
- nnhjs
Expand Down
30 changes: 30 additions & 0 deletions packages/router/__tests__/match-path-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { matchPath } from "@remix-run/router";

describe("matchPath", () => {
describe("given a pattern with optional parameters", () => {
it("matches paths with or without these optional parameters", () => {
const pattern = { path: "/foo/:bar?/:baz?" };

expect(matchPath(pattern, "/foo/bar/baz")).toEqual({
params: { bar: "bar", baz: "baz" },
pathname: "/foo/bar/baz",
pathnameBase: "/foo/bar/baz",
pattern
});

expect(matchPath(pattern, "/foo/bar")).toEqual({
params: { bar: "bar", baz: "" },
pathname: "/foo/bar",
pathnameBase: "/foo/bar",
pattern
});

expect(matchPath(pattern, "/foo")).toEqual({
params: { bar: "", baz: "" },
pathname: "/foo",
pathnameBase: "/foo",
pattern
});
});
});
});
6 changes: 3 additions & 3 deletions packages/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -962,10 +962,10 @@ function compilePath(
path
.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
.replace(/^\/*/, "/") // Make sure it has a leading /
.replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars
.replace(/\/:(\w+)/g, (_: string, paramName: string) => {
.replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
.replace(/\/:(\w+)(\??)/g, (_: string, paramName: string, optional: string) => {
paramNames.push(paramName);
return "/([^\\/]+)";
return `/${optional}([^\\/]+)${optional}`;
});

if (path.endsWith("*")) {
Expand Down

0 comments on commit cb83034

Please sign in to comment.