(continued from Composable Types without Unions in GraphQL (1 of 4))
If the number of types is obvious, small, and not likely to change, then one option to model Union types is to be explicit about each relationship.
Here, you can model a User type that has relationships with the favorites of movies, shows, and books.
type User {
name: String!
favoriteMovies: [Movie]! @relation
favoriteShows: [Show]! @relation
favoriteBooks: [Book]! @relation
# ...
}
type Movie {
title: String!
newRelease: Boolean
# ...movie fields
favoritedBy: [User]! @relation
}
type Show {
title: String!
newRelease: Boolean
# ...TV show fields
favoritedBy: [User]! @relation
}
type Book {
title: String!
newRelease: Boolean
# ...book fields
favoritedBy: [User]! @relation
}
type Query {
moviesByNewRelease(newRelease: Boolean!): [Movie]!
showsByNewRelease(newRelease: Boolean!): [Show]!
booksByNewRelease(newRelease: Boolean!): [Book]!
}
While this method can lead to some verbose queries, you are able to satisfy the objectives.
- ✅ query for all entities of a given type
- Each entity has its own type, so they can be queries separately.
- ✅ query for all entities with certain properties
- You can make multiple queries to get all of the results.
- Indexes are added to Fauna using fields on the
Query
type to support search by field such as thenewRelease
field that is shown.
- ✅ query for all relationships of an entity, regardless of which type it points to
- You can search for all user favorites by selecting each relationship field.
- You can search for all users that have favorited the media item, since each type has that field.
In the series:
This article is part of a series. Be sure to read the rest for different methods of modeling unions in GraphQL with Fauna.
- Composable Types without Unions in GraphQL (1 of 4)
- Modeling Unions in GraphQL (2 of 4)
- Modeling Unions as Sparse fields in GraphQL (3 of 4)
- A "Component" Pattern for GraphQL (4 of 4)