Unions in GraphQL
Introduction
In GraphQL, unions provide a way to define a field that can return different object types. This allows for a more flexible schema that can cater to various use cases.
What are Unions?
Unions in GraphQL are a special type that allows a field to return one of multiple possible types. Unlike interfaces, unions do not require the types to share any common fields.
Note: Unions are useful when you have disparate types that do not share a common structure but need to be grouped together under a single query response.
Defining Unions in GraphQL
To define a union, use the union
keyword followed by the union name and the types it can resolve to.
union SearchResult = User | Post | Comment
type User {
id: ID!
name: String!
}
type Post {
id: ID!
title: String!
}
type Comment {
id: ID!
content: String!
}
Using Unions in Queries
When querying a union, you need to use inline fragments to specify which type you want to retrieve.
query {
search(text: "GraphQL") {
... on User {
id
name
}
... on Post {
id
title
}
... on Comment {
id
content
}
}
}
Best Practices
- Keep union types to a minimum; too many types can complicate the schema.
- Use clear naming conventions for union types to convey their purpose.
- Document the possible types and their fields properly for better usability.
FAQ
Can a union contain interfaces?
No, unions can only contain object types and cannot include interfaces.
How do you handle errors with unions?
Handle errors externally by checking the type of the response in your application logic.