zod-to-openapi icon indicating copy to clipboard operation
zod-to-openapi copied to clipboard

Zod Error Schema

Open polaroidkidd opened this issue 1 year ago • 1 comments

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?

polaroidkidd avatar Sep 24 '24 13:09 polaroidkidd

@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?

AGalabov avatar Oct 04 '24 10:10 AGalabov

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.

polaroidkidd avatar Oct 06 '24 09:10 polaroidkidd