elierotenberg / fastify-zod

Zod integration with Fastify
MIT License
212 stars 19 forks source link

Nullable Zod Object Errors Out #44

Open KarlGNassar opened 1 year ago

KarlGNassar commented 1 year ago

I want the final response of the API to look something like this:

{
  "user": { "email": "string", "name": "string" },
  "parent": { "email": "string", "name": "string"} | null
}

So the parent can be nullable, I define my schema like this:

export const getUserByIdResponseSchema = z.object({
  user: z.object(userCore),
  parent: z.object(userCore).nullable(),
});

When the parent is actually null, the response is like expected:

{
    "user": {
        "id": 3,
        "email": "karl@email.com",
        "name": "karl nassar"
    },
    "parent": null
}

But when there is an actual parent, the error message states The values of <schema> does not match schema definition

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "The value of '#/definitions/getUserByIdResponseSchema/properties/parent' does not match schema definition."
}

Is there any way to explicitly tell fastify-zod to safeParse the object?