feat: add support for optional dynamic route params (#1706)

This commit is contained in:
Michael Herzner
2023-09-07 14:28:44 +02:00
committed by GitHub
parent cda20720dd
commit 8a0d0dc452
6 changed files with 179 additions and 108 deletions
+26 -1
View File
@@ -1159,6 +1159,7 @@ export function pathToPattern(path: string): string {
);
}
// Case: /[[id]].tsx
// Case: /[id].tsx
// Case: /[id]@[bar].tsx
// Case: /[id]-asdf.tsx
@@ -1166,12 +1167,36 @@ export function pathToPattern(path: string): string {
// Case: /asdf[bar].tsx
let pattern = "";
let groupOpen = 0;
let optional = false;
for (let j = 0; j < part.length; j++) {
const char = part[j];
if (char === "[") {
if (part[j + 1] === "[") {
// Disallow optional dynamic params like `foo-[[bar]]`
if (part[j - 1] !== "/" && !!part[j - 1]) {
throw new SyntaxError(
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
);
}
groupOpen++;
optional = true;
pattern += "{/";
j++;
}
pattern += ":";
groupOpen++;
} else if (char === "]") {
if (part[j + 1] === "]") {
// Disallow optional dynamic params like `[[foo]]-bar`
if (part[j + 2] !== "/" && !!part[j + 2]) {
throw new SyntaxError(
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
);
}
groupOpen--;
pattern += "}?";
j++;
}
if (--groupOpen < 0) {
throw new SyntaxError(`Invalid route pattern: "${path}"`);
}
@@ -1180,7 +1205,7 @@ export function pathToPattern(path: string): string {
}
}
route += "/" + pattern;
route += (optional ? "" : "/") + pattern;
}
// Case: /(group)/index.tsx