fastify-sensible icon indicating copy to clipboard operation
fastify-sensible copied to clipboard

Strict schema validation of methods fails

Open ollebergkvist opened this issue 4 months ago • 3 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.28.1

Plugin version

5.6.0

Node.js version

20.17.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.7.6

Description

I noticed that when I add .strict() schema validation in my response schemas (zod), reply.*() breaks.

Eg. reply.unauthorized() returns this response:

{
	"statusCode": 401,
	"error": "Unauthorized",
	"message": "Unauthorized"
}

This fails:

export const routeSchema = {
  response: {
    401: z
      .object({
        statusCode: z.literal(401),
        error: z.literal('Unauthorized'),
        message: z.string()
      }).strict()
    }
}

With this error:

{
	"statusCode": 500,
	"code": "FST_ERR_FAILED_ERROR_SERIALIZATION",
	"message": "Failed to serialize an error. Error: Response doesn't match the schema. Original error: Unauthorized"
}

This works:

export const routeSchema = {
  response: {
    401: z
      .object({
        statusCode: z.literal(401),
        error: z.literal('Unauthorized'),
        message: z.string()
      })
    }
}

Link to code that reproduces the bug

No response

Expected Behavior

Should be possible to add strict validation.

ollebergkvist avatar Oct 11 '24 17:10 ollebergkvist