turkerdev / fastify-type-provider-zod

MIT License
386 stars 24 forks source link

z.number() not works in querystring #50

Closed foxgem closed 1 year ago

foxgem commented 1 year ago

Hi, here is the schema I defined

{
  path: '/echo',
  method: 'get',
  schema: {
    querystring: z.object({
      id: z.number(),
    }),
    response: {
      200: z.object({
        id: z.number(),
      }),
    },
  },
  handler: (req, res) => {
    res.status(200).send({id: (req.body as any).id});
  },
}

However, it always complained 400 for curl "http://localhost:3006/echo?id=123"

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "[\n  {\n    \"code\": \"invalid_type\",\n    \"expected\": \"number\",\n    \"received\": \"string\",\n    \"path\": [\n      \"id\"\n    ],\n    \"message\": \"Expected number, received string\"\n  }\n]"
}

But, when I changed id in querystring to z.string(), everything is fine. Could you point out what's wrong?

Thanks

kibertoad commented 1 year ago

querystrings only pass strings, because there is no way for a client to tell if something is a number or a boolean. what you are looking for is coercing, to convert this string into a number. See https://zod.dev/?id=coercion-for-primitives

foxgem commented 1 year ago

@kibertoad thanks for quick response!

According to this link: https://webapplicationconsultant.com/javascript/how-to-parse-boolean-or-numeric-values-in-fastify-query-string/ , it looks like fastify schema can convert the type automatically?

kibertoad commented 1 year ago

if you are using zod, fastify conversion, which relies on ajv, is not going to work, you need to use zod mechanisms instead

foxgem commented 1 year ago

thanks, I will close this, :).

jsnimda commented 1 week ago

@foxgem I created a plugin because of this, so that you can use z.boolean() or z.number() on querystring, feel free to take a look :D https://www.npmjs.com/package/fastify-zod-query-coercion