Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allOf through z.extend with refs / union actually anyOf #365

Closed
jakobfenerparc opened this issue Nov 14, 2024 · 2 comments
Closed

allOf through z.extend with refs / union actually anyOf #365

jakobfenerparc opened this issue Nov 14, 2024 · 2 comments

Comments

@jakobfenerparc
Copy link

Hi Sam,

amazing library, happy to see something being to actively developed.
More a question since it's not clear from the README documentation.

In the documentation it says that a z.union translates into allOf (unless globally configured to oneOf through the unionOneOf setting).
I think this should be changed to anyOf as the code suggests.

My actual question:
In my case I need to (for compatability reasons) create an allOf schema, which consists of multiple refs and some custom type.

    MySchema:
      allOf:
        - $ref: "#/components/schemas/Base1"
        - $ref: "#/components/schemas/Base2"
        - type: object
          required:
            - prop1
          properties:
            prop1:
              type: string
              description: Description1

I tried to get this by using extend as mentioned in the docs.
But the multiple refs are a problem, because when doing this:

const Base1 = z.object({ a: z.string(), b: z.number() }).openapi({ ref: "Base1" });
const Base2 = z.object({ c: z.string() }).openapi({ ref: "Base2" });
const MySchema = Base1.extend(Base2.shape).extend(z.object({ prop1: z.string() }))

I get a ref for Base1, but since .shape flattens Base2 the openapi information gets lost, so Base2 and the last z.object get merged inline into MySchema.

Is there a different way of constructing the openapi schema above (with the allOf refs) that I did not see?

@samchungy
Copy link
Owner

Ah yep you caught a mistake, I'll get onto fixing it.

Hmmm yeah that's tricky, unfortunately yeah passing in the shape means we can't infer where it came from.

#360

You could potentially use .and()?

@jakobfenerparc
Copy link
Author

z.and works just right, thanks.
Apart from the docs, this issue solved I guess.

Thanks for !instant feedback!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants