asteasolutions / zod-to-openapi

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

Handling of multiple chained `regex` calls #169

Closed samkio closed 1 year ago

samkio commented 1 year ago

I'm not sure if this is possible but I would like clarity on how this works or how it should work.

If we imagine a schema such as:

z.string()
      .regex(pattern1, "Must match this regex")
      .regex(pattern2, "And this regex too")

Then after transforming we get a pattern of pattern1 in the OpenAPI spec. i.e. pattern2 is lost here. The issue being that whilst zod supports multiple regex checks, OpenAPI spec only allows for one. Other zod to openapi libraries either have this semantic or try to combine the two patterns.

What should the semantic be here? Was it intentional that the first pattern is picked? Or should it attempt to combine the regex patterns? Something like (?=match this expression)(?=match this too) could be clear in terms of documentation?

I raise this as we have scenarios where we have multiple regex checks and the generated docs could be misleading.

AGalabov commented 1 year ago

Hey @samkio I've never though of such a scenario. I'd have to look at the code and the produced document.

I also need to answe myself "What does two chained regex mean - is it an "or" or is it an "and" operation". I imagine it should be "and". If we can combine it that might be ideal.

For the time being I'd suggest you use the .openapi method to maunally fix those cases since I am unsure on what the resolution here would be. I'll get back as soon as I can

samkio commented 1 year ago

Hey @AGalabov ,

Thanks for taking a look. My understanding is that it is an "and", but I suppose someone could create more complex schemas with .and and .or in zod.

Potentially this would be difficult to automate and manually fixing, as you've suggested, may be the best option in these scenarios.

AGalabov commented 1 year ago

@samkio as you mentioned I think it would be much cleaner for us to leave such a special case to the "user" instead of guessing and making a best effort of "matching it" and potentionally generating something wrong.

I'll be closing the issue. And still thank you for bringing it up and using our library