Today I want to show you how you can use discriminated unions for input types in GraphQL through the OneOf specification.
Disclaimer: The OneOf specification is still in draft, so it is possible that it will still change or not become a part of the GraphQL specification.
Let me first start by explaining the use case where I want to apply this features. In our GraphQL api , we have multiple root queries that can be queried either through the technical id(an integer) and the business key(a string). Our original API looked something like this:
A consumer of this API should either use the id or the business key but I could not prevent the user from using both:
To handle this situation I throw an error when the user tries to invoke the GraphQL query providing both arguments:
This is a perfect case that can be improved through the usage of OneOf. By using OneOf on an input object we tell GraphQL that only one field of the input object can be set.
In a schema first approach, we add the OneOf directive to our input object:
Or we use the code first approach in HotChocolate to achieve the same result:
Now of course we need to update our implementation to use this input object:
If we now try to pass multiple arguments, GraphQL will prevent this:
Nice!