asteasolutions / zod-to-openapi

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

Conditional use of "oneOf" instead of "anyOf" for particular z.union #236

Open M1r1k opened 4 months ago

M1r1k commented 4 months ago

First, thank you for the great library!

I went through all related issues and PRs about but did not find anything :)

I have a case where z.union() is used not for different object structures but for object vs string:

const t = z.union([
 z.string(),
 z.object({ prop1: z.string() }),
 ]);

That generates OpenAPI like this:

anyOf:
  - type: string
  - type: object
    properties:
      prop1:
        type: string
    required:
      - prop1

Which ends up as

export type T = Partial<string> & Partial<{ prop1: string }>;

And I understand that in some cases it makes sense, but when different data formats are compared I need oneOf instead. So is there any "smart" way to alter OpenAPI generation? So far I see only post-processing OpenAPIObject as a way to conditionally alter this behaviour

Thanks in advance!

arjunyel commented 3 months ago

@M1r1k also hitting this, what did you mean by post-processing the OpenAPIObject?