ethanniser / next-typesafe-url

Fully typesafe, JSON serializable, and zod validated URL search params, dynamic route params, and routing for NextJS.
https://next-typesafe-url.dev
MIT License
362 stars 16 forks source link

Custom format options #72

Closed ru-van-urk closed 10 months ago

ru-van-urk commented 10 months ago

WIP Custom options

I was moving over my old solution to next-typesafe-url when I ran into a missing feature. Basically I would love to add some custom options to the way next-typesafe-url formats the string. For example: /foo?countries=NL~UK~DE will be correctly formatted to an array. I made a basic working solution but before I continue I want to put it here.

This pull request is by no means complete but I would love to get some feedback before I continue working on it.

This pull request adds an extra option to the Route in which we can define a custom arraySeparator:

import { z } from "zod";
import { type DynamicRoute } from "next-typesafe-url";

const COUNTRIES = ["NL", "UK", "US", "DE", "FR"] as const;

export const Route = {
  searchParams: z.object({
    countries: z.array(z.enum(COUNTRIES)).optional(),
  }),
  options: {
    format: {
      arrayFormatSeparator: "~",
    },
  },
} satisfies DynamicRoute;

export type RouteType = typeof Route;

With this in place the arrays are now joined with this separator instead of JSONfying it.

Todo's:

Ideas:

Thoughts:

ethanniser commented 10 months ago

Thank you for the pull request, however I am not totally in love with this solution, as it creates a disconnect between how data is serialized and deserialized, as well as putting all of the ownership for every possible new formatting option on us.

I think there is absolutely a place for allowing the user to provide a custom global serializer/deserializer, which I believe would address your issue. I have created an issue to track that: #77

as a side note, would it be possible to adjust your prettier config to match the projects for any future contributions? It is really hard to review the diff with a bunch of prettier comma changes.

actually, we don't have a prettier config: #78