Route generator/static routing #318
Faithfinder
started this conversation in
Ideas
Replies: 1 comment
-
I am actively investigating a typesafe url builder :)
Tanner Linsley
…On Aug 26, 2022, 7:50 AM -0600, Dmitrii Kartashev ***@***.***>, wrote:
Sorry, not sure what the official name is, but I would really like a tool that good generate the links for me.
Easier to show an example:
// routes = current routes
const links = generateLinks(routes)
<Link to={links.author.posts(postId)}>See posts</Link>
Right now we wrote this tool for the same purpose, but it's a bit clumsy and doesn't support nested routes:
import { String, Union } from 'ts-toolbelt';
const basePath = import.meta.env.VITE_BASE_URL ?? '';
export const createRoute = <TPath extends string>(route: TPath) => ({
template: attachBasePathIfrelative(route),
link: (...args: ArgParams<TPath> extends undefined ? [] : [ArgParams<TPath>]) => replaceRouteParams(route, args[0]),
});
const replaceRouteParams = (route: string, params: Record<string, string> = {}) => {
const routeParams = route.match(/:([a-zA-Z0-9]+)/g);
if (!routeParams) {
return attachBasePathIfrelative(route);
}
return routeParams.reduce((route, param) => {
const paramName = param.replace(':', '');
const paramValue = params[paramName];
if (!paramValue) {
throw new Error(`Missing route parameter: ${paramName}`);
}
return route.replace(param, paramValue);
}, attachBasePathIfrelative(route));
};
const attachBasePathIfrelative = (route: string) => {
if (route.startsWith('http')) {
return route;
}
return `${basePath}${route}`;
};
// This split a string like /path/:id/to/:name into { id: string, name: string }
type Param = `:${string}`;
type PathArray<TPath extends string> = String.Split<TPath, '/'>;
type PathParams<TPath extends string> = {
[Folder in PathArray<TPath>[number]]: Folder extends Param
? {
[Key in String.Split<Folder, ':'>[1]]: string;
}
: never;
}[PathArray<TPath>[number]];
type FinalParams<TPath extends string> = Union.Merge<PathParams<TPath>>;
type ArgParams<TPath extends string> = keyof FinalParams<TPath> extends never ? undefined : FinalParams<TPath>;
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you are subscribed to this thread.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Sorry, not sure what the official name is, but I would really like a tool that could generate the links for me.
Easier to show an example:
Right now we wrote this tool for the same purpose, but it's a bit clumsy and doesn't support nested routes:
Beta Was this translation helpful? Give feedback.
All reactions