feat: add support for optional dynamic route params (#1706)
This commit is contained in:
+26
-1
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user