ProNextJS/declarative-routing

safeParse for searchParams

Opened this issue · 6 comments

the getting/parsing of searchParams is a bit cumbersome: example
Adding a function that safeparses to the searchSchema would be nice.

found something with query-string
it makes sure that all params that can be parsed will be parsed (partial parse)

export function safeParseSearchParams<T extends z.AnyZodObject>(schema: T, request: NextRequest): Partial<z.infer<T>> {
  const params = queryString.parse(request.nextUrl.search, { parseBooleans: true })
  const shape = schema.shape;
  const parsed: Record<string, any> = {};

  for (const key in shape) {
    if (shape.hasOwnProperty(key)) {
      const fieldSchema: ZodTypeAny = shape[key];
      const result = fieldSchema.safeParse(params[key])
      if (result.success)
        parsed[key] = result.data;
    }
  }

  return parsed;
}

Nice! So this would be an included helper function that can be used for search params validation?

Oh yeah, just plug in the schema and the NextRequest. Then query-string parses the searchString into an object. Every field of that object then gets validated and potentially removed, so only valid searchParams make it. The kinda least destructive approach I thought...

I didn't check if zod throws errors on fields it doesn't cover, gotta check that. I think there could also be some error handling/logging to give feedback on which parse failed, but right now it serves its purpose^^

damn i just realized you already use query-string... since you're only using stringify is there anything against fast-querystring?
https://www.npmjs.com/package/fast-querystring
And I created a version that doesn't use any querystring parser.

Also are there any rules you want to apply for booleans? what should be considered as true? "true" or just the mentioning of the key?
I also think it would be an antipattern to use nested values like array[foo][bar[baz] in a querystring. I'd rather want to enforce it to be part of a json body when the object is more complex than just a couple strings, bools and numbers.

PR is coming shortly ;-)

pff perfect now i see zod.coerce^^ goddammit...

alright looks like i will take some more time for an updated version ;-)