mm-ninja-turtles / turtle-express

My attempt of making Express.JS a typesafe router with Zod.
3 stars 0 forks source link

[feature]: zod validation for params and query of request object of handler #50

Closed PyaePhyoKyaw61194 closed 2 years ago

PyaePhyoKyaw61194 commented 2 years ago

I am thinking about zod. For query strings and params , I guess we can only valid them as z.string() always. Since they are passed as strings. But when we use zod, we can get the advantage of validating the null if the required params or query strings are not sent from request. I guess we got no choice for enhancement here. Any suggestions?

wai-lin commented 2 years ago

@PyaePhyoKyaw61194

I think you can just use zod's refine for custom validations or minValue: 1 for the none empty string if you want to.

eg.

// Option 1
z.object({
  limit: z.string().refind((val) => val.length < 1, { message: 'limit is required.' })
})

// Option 2
z.object({
  limit: z.string().min(1, { message: 'limit is required' })
})

I think this is what you're referring to.

PyaePhyoKyaw61194 commented 2 years ago

Yeah, I accidentally set

query: z.object({
        limit: z.number(),
    }),

I just forget the query values will always be passed as strings.

wai-lin commented 2 years ago

This is the part where we need to highlight in documentation. So that most users will not face the same problem.

wai-lin commented 2 years ago

I guess this should be solved with the usage of z.string(). And wiki is also updated to use z.string() for both params and query schema. I'll close the issue.