schemars
schemars copied to clipboard
Internally Tagged Enum Definitions
Hey I'm trying to generate typescript types from the generated JSON schema and am running into a bit of a design constraint.
Basically the generated type for an enum that has [#serde(tag="...")] gets turned into an anyOf where the resulting types are directly mentioned without them being given a definition. This is in contrast from for instance using [#serde(tag="t", content="c")] where a new definition is inserted for every type of content.
When generating Typescript the latter is much more convenient since you get a discriminated union where you can still refer to each individual item since they will be named. In contrast the former just gives a giant union blob where it's hard to do things like casting to a specific type.
I would like to figure out a way we can make the JSON schema more verbose and essentially generate definitions for every enum item. Happy to make a PR if someone can point me in the right direction of where to find the relevant code bits.
@RXminuS did you ever resolve this query?
@GREsau what would the difficulty of implementing this be? If we have a checklist here we could work on it in a PR.
- [x] create test based on internally tagged enum to include discriminator
- [ ] add 'discriminator' option to OpenAPI schema settings definition to enable/disable generation of property
- [x] find out where parsed serde attributes are stored / used -> expr_for_internal_tagged_enum()#191
- [ ] make sure every instance has the 'type' property referred by the 'discriminator'
- [ ] create Visitor implementation to add this property to schema
- [ ] have Visitor set the discriminator based on whether the serde struct is tagged
- [ ] ...
See https://github.com/parture-org/schemars/tree/openapi-discriminator for WIP
This would be really nice to have
I have done some research into this and summarized it here. It has a manual workaround to this issue. It would still be nice to have the PR finished up and merged 👍