turkerdev / fastify-type-provider-zod

MIT License
413 stars 25 forks source link

validation fail for params of type numbers. expects a string #72

Open alzalabany opened 10 months ago

alzalabany commented 10 months ago

example: the following route if you open http://127.0.0.1:3003/x/12 it will fail expected number, received string.

fastify.withTypeProvider<ZodTypeProvider>().get("/x/:n", {
    schema: {
      params: z.object({ n: z.number() }),
      response: {
        200: z.object({ n: z.number() }),
      },
    },
    handler: ({ params: { n } }) => {
      return { n };
    },
  });
kibertoad commented 10 months ago

You need to use .coerce for query and path params, as these always are passed as strings, because fastify has no way to establish their true type

zhangskills commented 8 months ago

example: the following route if you open http://127.0.0.1:3003/x/12 it will fail expected number, received string.

fastify.withTypeProvider<ZodTypeProvider>().get("/x/:n", {
    schema: {
      params: z.object({ n: z.number() }),
      response: {
        200: z.object({ n: z.number() }),
      },
    },
    handler: ({ params: { n } }) => {
      return { n };
    },
  });

just like this:

fastify.withTypeProvider<ZodTypeProvider>().get("/x/:n", {
    schema: {
        params: z.object({n: z.coerce.number()}),
        response: {
            200: z.object({n: z.number()}),
        },
    },
    handler: ({params: {n}}) => {
        return {n};
    },
});