Skip to content

Commit

Permalink
Support optional route params (#32)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
brandonpittman and sandulat authored Jan 8, 2023
1 parent d934b00 commit 661c878
Show file tree
Hide file tree
Showing 4 changed files with 432 additions and 230 deletions.
2 changes: 1 addition & 1 deletion packages/routes-gen-remix/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"routes-gen": "*"
},
"devDependencies": {
"@remix-run/dev": "^1.0.3",
"@remix-run/dev": "^1.9.0",
"config": "*"
},
"peerDependencies": {
Expand Down
18 changes: 16 additions & 2 deletions packages/routes-gen/src/export-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,17 @@ export const exportRoutes = ({
.map((route) => {
const params = extractPathParams(route.path);

const onlyOptionalParams =
params.length > 0 && params.every((param) => param.endsWith("?"));

return ` | ["${route.path}"${
params.length > 0 ? `, RouteParams["${route.path}"]` : ""
}]`;
}]${
onlyOptionalParams
? `
| ["${route.path}"]`
: ""
}`;
})
.join("\n");

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

return ` "${route.path}": ${
params.length > 0
? `{ ${params.map((path) => `"${path}": string`).join(", ")} }`
? `{ ${params
.map((param) =>
param.endsWith("?")
? `"${param.slice(0, -1)}"?: string`
: `"${param}": string`
)
.join(", ")} }`
: "Record<string, never>"
};`;
})
Expand Down
12 changes: 7 additions & 5 deletions packages/routes-gen/src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ export function route<T extends string>(
params?: Record<string, any>
): T {
if (params) {
return Object.entries(params).reduce(
(result, [key, value]) =>
result.replace(new RegExp(`:${key}`, "g"), value),
path as string
) as T;
return Object.entries(params)
.reduce(
(result, [key, value]) =>
result.replace(new RegExp(`:${key}\\??`, "g"), value),
path as string
)
.replace(new RegExp("\\/:.+\\?", "g"), "") as T;
}

return path;
Expand Down
Loading

0 comments on commit 661c878

Please sign in to comment.