asteasolutions / zod-to-openapi

A library that generates OpenAPI (Swagger) docs from Zod schemas
MIT License
955 stars 60 forks source link

Zod Error Schema #260

Open polaroidkidd opened 1 month ago

polaroidkidd commented 1 month ago

Hi

First of all, great work on this library. I'm sort of angry I found it because now I'm rewriting my API Spec :sweat_smile:

Anyway, I have an endpoint that returns the z.ZodError type and I wanted to ask if you happend to know of a simple way of generating specific zod error schemas from existing schemas?

AGalabov commented 1 month ago

@polaroidkidd thank you for the kind words. I am not sure I understood your question. Do you want to create a specific ZodError instance based on an error of a OpenAPI specification?

polaroidkidd commented 1 month ago

Right now I created this error schema based on the docs. It looks like this.

export const ZodErrorSchemaDTO = z.object({
    name: z.string(),
    issues: z.array(
        z.object({
            code: z.string(),
            expected: z.string(),
            received: z.string(),
            path: z.array(z.string()),
            message: z.string()
        })
    )
});

It's all strings, which is fine for a generic error. But I was wondering if it would be possible to extract the possible errors from other schemas, like this one for example

export const CollectionWithRelationsDTO: z.ZodType<CollectionWithRelationsDTO> =
    CollectionOptionalDefaultsSchema.merge(
        z.object({
            items: ItemDTO.array().default([]),
            User: UserDTO,
            parent: CollectionOptionalDefaultsSchema.optional(),
            children: CollectionOptionalDefaultsSchema.array().default([]),
            tags: TagOptionalDefaultsSchema.array().default([])
        })
    );

I realise that this is not a issue specific to zod-to-openapi but I thought I'd ask here since you guys probably have a better Idea of how to create error response codes from APIs.