(continued from Modeling Unions in GraphQL (2 of 4))
One method to model a union is to provide all fields for all entities on the same type. This is especially useful if the various entities share many properties. When creating or updating an entity of a given type, only the fields related to that type are provided, while the rest remain null
. You can provide a String or Enum “type” or “tag” field that identifies the entity as a certain type of item.
type User {
name: String!
favorites: [MediaItem]! @relation
# ...
}
enum MediaType {
MOVIE
SHOW
BOOK
}
type MediaItem {
type: MediaType!
title: String!
newRelease: Boolean
# ...movie fields
# ...show fields
# ...book fields
favoritedBy: [User]! @relation
}
type Query {
itemsByType(type: MediaType!): [MediaItem]!
itemsByNewRelease(newRelease: Boolean!): [MediaItem]!
}
The downsides to this are fairly clear: you lose control over type validation in GraphQL; your app has to do a lot more heavy lifting to validate and manage your various types.
However, you still satisfy the objectives:
- ✅ query for all entities of a given type
- You can get all items of a type by indexing on a “type” or “tag” field.
- ✅ query for all entities with certain properties
- Every entity is searchable by every property.
- 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 the single
favorites
field. - You can search for all users that have favorited the media item through the
favoritedBy
field.
- You can search for all user favorites by selecting the single
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)