remix-routes
remix-routes copied to clipboard
Add a way to validate params using Zod
I use a setup such as:
const SearchParamsSchema = z.object({
view: z.enum(["list", "grid"]),
sort: z.enum(["price", "size"]).optional(),
page: z.number().int().optional(),
})
export type SearchParams = z.infer<typeof SearchParamsSchema>;
The problem that I am running into is that $path
does not perform runtime validation of the parameters, i.e. sometimes the generated URLs are invalid.
I am able to catch them on the receiving route. However, in terms of being able to locate the origin of the issue, it would preferable if $path
itself performed validation.
In this specific case, I was able to locate the original error site with this:
export const getPath = <
Route extends keyof Routes,
Rest extends {
params: Routes[Route]['params'];
query?: Routes[Route]['query'];
},
>(
...args: Rest['params'] extends Record<string, never>
? [route: Route, query?: Rest['query']]
: [route: Route, params: Rest['params'], query?: Rest['query']]
): RelativeUrl => {
const path = $path(...args);
assertRelativeUrl(path);
const sortedSearchParams = sortRelativePathSearchParams(path);
// Detect when we generate an invalid URL
if (sortedSearchParams.includes('undefined')) {
throw new Error('Undefined search parameter');
}
return sortedSearchParams;
};