fastify-type-provider-zod icon indicating copy to clipboard operation
fastify-type-provider-zod copied to clipboard

validation fail for params of type numbers. expects a string

Open alzalabany opened this issue 1 year ago • 2 comments

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 };
    },
  });

alzalabany avatar Jan 13 '24 16:01 alzalabany

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

kibertoad avatar Jan 13 '24 16:01 kibertoad

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};
    },
});

zhangskills avatar Mar 20 '24 03:03 zhangskills