turkerdev / fastify-type-provider-zod

MIT License
337 stars 21 forks source link

Fix safeParse error on reply validation #15

Closed kibertoad closed 2 years ago

kibertoad commented 2 years ago

fixes #3

kibertoad commented 2 years ago

@turkerdev Can you please take a look?

turkerdev commented 2 years ago

@turkerdev Can you please take a look?

I am not at home currently, let me take a look when i get home, probably 2 days later.

kibertoad commented 2 years ago

@alxarch Where does

    200: z.object({
       status: z.kiteral("OK"),
       ...
   }),
   500: z.object({
       status: z.literal("ERROR"),
       error: z.object({...}),
       ...
   }),

come from? Reply structure can be pretty much anything

alxarch commented 2 years ago

z.object({ status: z.literal("ERROR"), error: z.object({...}), ... }),

If you take a look at the docs here provides an httpStatus property. It seems that this form is needed to be able to have separate validation based on status code.

The serializerCompiler in the current form of the code does not take httpStatus parameter into account. AFAICT in order to be compatible with the default JSON Schema behavior, the serializerCompiler must pick the correct schema value from a {[statusCode string|number]: ZodTypeAny} in schema.response. At least that's how I solved it in a local workaround experiment a few weeks back.

kibertoad commented 2 years ago

@alxarch I'm not seeing this. Example that fastify is giving is this:

  schema: {
    response: {
      '2xx': {
        id: { type: 'number' },
        name: { type: 'string' }
      }
    }
  }

there is no statusCode present here, it seems to be exactly what we are currently using.

httpStatus is something that serializer is receiving from fastify, and I think it should already be passed. What would you do differently than what we do now based on this documentation?

alxarch commented 2 years ago

I was referring to the httpStatus in the setSerializerCompiler signature. Let me check out the branch and will get back to you after I compare it to my workaround. I might have used a different approach in my experiment that is not relevant to how it is being solved here.


fastify.setSerializerCompiler(({ schema, method, url, httpStatus }) => {
  return data => JSON.stringify(data)
 })
kibertoad commented 2 years ago
fastify.setSerializerCompiler(({ schema, method, url, httpStatus }) => {
  return data => JSON.stringify(data)
 })

Doesn't this completely bypass any validation?

kibertoad commented 2 years ago

@turkerdev Thank you! Can you publish a new version now?

alxarch commented 2 years ago

@kibertoad tried the released version and it seems to work as intended! :tada: Sorry for any confusion I might have caused.