GraphQL
Unions and Enums
One of several different types, and a fixed set of values.
Unions
A union says "this field returns one of these types", and the types need nothing in common. Perfect for search results and for "result or error":
type Book { title: String! isbn: String! }
type Author { name: String! born: Int }
union SearchResult = Book | Author
type Query { search(q: String!): [SearchResult!]! }@Query fun search(q: String): List<Any> = books.matching(q) + authors.matching(q) // Book and Author objects{ search(q: "herbert") { __typename ... on Book { title } ... on Author { name born } } }Because members share no fields you must always use fragments (... on Book) to read anything, and __typename tells the client which one it got. The concrete type is found like for interfaces.
Results that can fail are a good use:
union PlaceOrderResult = Order | OutOfStock | PaymentDeclinedThe client switches on __typename: expected outcomes are data, not errors.
Enums
An enum is a fixed set of allowed values:
enum OrderStatus { PENDING PAID SHIPPED CANCELLED }
type Order { id: ID! status: OrderStatus! }
type Query { orders(status: OrderStatus): [Order!]! }enum class OrderStatus { PENDING, PAID, SHIPPED, CANCELLED }
@Query fun orders(status: OrderStatus?): List<Order> = ... // a Kotlin or Java enum travels by NAMEAn unknown value (orders(status: SLEEPING)) is rejected by GraphQL before your code runs, with an error listing the valid values, so you never validate it yourself. Add a value in the schema and the enum together: the names must match exactly.
Code-first
@GqlUnion and an enum class generate these for you: Generating SDL.