Skip to content

Commit 661c878

Browse files
Support optional route params (#32)
* Support optional route params * Fix route function to strip optional params syntax * feat(routes-gen): polish optional params support Co-authored-by: Stratulat Alexandru <[email protected]>
1 parent d934b00 commit 661c878

File tree

4 files changed

+432
-230
lines changed

4 files changed

+432
-230
lines changed

packages/routes-gen-remix/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"routes-gen": "*"
2323
},
2424
"devDependencies": {
25-
"@remix-run/dev": "^1.0.3",
25+
"@remix-run/dev": "^1.9.0",
2626
"config": "*"
2727
},
2828
"peerDependencies": {

packages/routes-gen/src/export-routes.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,17 @@ export const exportRoutes = ({
2323
.map((route) => {
2424
const params = extractPathParams(route.path);
2525

26+
const onlyOptionalParams =
27+
params.length > 0 && params.every((param) => param.endsWith("?"));
28+
2629
return ` | ["${route.path}"${
2730
params.length > 0 ? `, RouteParams["${route.path}"]` : ""
28-
}]`;
31+
}]${
32+
onlyOptionalParams
33+
? `
34+
| ["${route.path}"]`
35+
: ""
36+
}`;
2937
})
3038
.join("\n");
3139

@@ -35,7 +43,13 @@ export const exportRoutes = ({
3543

3644
return ` "${route.path}": ${
3745
params.length > 0
38-
? `{ ${params.map((path) => `"${path}": string`).join(", ")} }`
46+
? `{ ${params
47+
.map((param) =>
48+
param.endsWith("?")
49+
? `"${param.slice(0, -1)}"?: string`
50+
: `"${param}": string`
51+
)
52+
.join(", ")} }`
3953
: "Record<string, never>"
4054
};`;
4155
})

packages/routes-gen/src/route.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@ export function route<T extends string>(
33
params?: Record<string, any>
44
): T {
55
if (params) {
6-
return Object.entries(params).reduce(
7-
(result, [key, value]) =>
8-
result.replace(new RegExp(`:${key}`, "g"), value),
9-
path as string
10-
) as T;
6+
return Object.entries(params)
7+
.reduce(
8+
(result, [key, value]) =>
9+
result.replace(new RegExp(`:${key}\\??`, "g"), value),
10+
path as string
11+
)
12+
.replace(new RegExp("\\/:.+\\?", "g"), "") as T;
1113
}
1214

1315
return path;

0 commit comments

Comments
 (0)