asteasolutions / zod-to-openapi

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

how to use custom TupleTransformer #221

Closed elee1766 closed 3 months ago

elee1766 commented 3 months ago

hi,

i was curious if it was possible to use a custom TupleTransformer for generating openapi spec without forking the project.

looking here - https://github.com/asteasolutions/zod-to-openapi/blob/master/src/transformers/tuple.ts

tuples seem to be represented as an anyOf with min/max items, however openapi3.1/jsonschema2020.12 supports prefixItems

i would like to output such prefixItems in my openapi spec.

It would be great if i could just use a custom tupletransformer in my code like:

      const { items } = zodSchema._def;
      const schemas = items.map(schema => this.generateSchemaWithRef(schema));
      return {
        ...this.mapNullableType('array', isNullable),
        prefixItems: schemas,
      };

which is giving me the behavior that i want.

I see that they are all private fields, with no obvious way to switch out a single transformer.

https://github.com/asteasolutions/zod-to-openapi/blob/master/src/transformers/index.ts#L27-L41C41

AGalabov commented 3 months ago

@elee1766 thank you for bringing this up. In general prefixItems are something that we looked into when implementing the tuple support - see the PR and the related comments here but at the time the support for it was scarce and we never really got to the point of implementing it. Note it is only valid for 3.1.0 and not for older ones.

The transformers are something new (merged them yesterday) and now that we have them your suggestion would be much easier to implement now.

However as for giving the option of a custom transformer - I don't see a reason for that behavior for now - since the transformation from zod to openapi is generally a deterministic process. So I'd rather try and implement that internally in the near future. If you have the time for it - please go ahead and raise a PR with some tests.

elee1766 commented 3 months ago

I'm currently using an old fork from before transformers with my patch to produce documents.

I do know it's 3.1 only which is why I floated the idea of using a custom transformer - to preserve compatibility such that 3.0/2.x can be generated still without too much problem

happy to open a PR but I'm not too sure what should be done... check the version and output accordingly? create a config option?

AGalabov commented 3 months ago

@elee1766 I got some free time and implemented it - feel free to check out the PR

AGalabov commented 3 months ago

@elee1766 this should now be available as part of the v7.0.0 Release :rocket: .