Given the following GraphQL schema snippet:
interface Character {
id: ID!
name: String!
}
type Human implements Character {
id: ID!
name: String!
homePlanet: String
}
type Droid implements Character {
id: ID!
name: String!
primaryFunction: String
}And this query:
{
characters {
id
name
... on Human {
homePlanet
}
... on Droid {
primaryFunction
}
}
}Assuming the data contains one Human and one Droid, what is the shape of the returned data?
Look at the inline fragments ... on Human and ... on Droid to see which fields are included for each type.
The query uses inline fragments to select fields specific to each implementing type of the Character interface. The Human has homePlanet and the Droid has primaryFunction. The result includes these fields only for the matching types.
In GraphQL, when a query requests a field of an abstract type (interface or union), how does the server determine which concrete type to use for each result item?
Think about how GraphQL knows which fields to return for each item when the type is abstract.
The GraphQL server uses the __typename field or a resolveType function defined in the schema to determine the concrete type of each item implementing an interface or union. This allows it to return the correct fields for that type.
Consider this GraphQL query fragment:
{
search(text: "robot") {
... on Human {
name
homePlanet
}
... Droid {
name
primaryFunction
}
}
}What is the syntax error in this fragment?
Check the syntax for inline fragments in GraphQL.
Inline fragments on abstract types require the keyword on before the type name. The fragment ... Droid is missing on and should be ... on Droid.
Given this schema:
interface Animal {
id: ID!
name: String!
}
type Dog implements Animal {
id: ID!
name: String!
breed: String
}
type Cat implements Animal {
id: ID!
name: String!
livesLeft: Int
}And this query:
{
animals {
id
name
... on Dog {
breed
}
... on Cat {
livesLeft
}
}
}The response returns null for breed and livesLeft fields for all animals. What is the most likely cause?
Think about how the server knows which concrete type each item is.
If the server does not implement or returns null from the resolveType function for the interface, it cannot determine the concrete type of each item. As a result, type-specific fields in inline fragments return null.
You have a GraphQL query that fetches a large list of items of an interface type with many inline fragments for different implementations. The query is slow because the server resolves the concrete type for each item individually. Which approach can optimize abstract type resolution performance?
Think about how to reduce repeated work on the server when resolving types.
Batching type resolution by grouping items of the same type reduces the number of calls to resolveType and improves performance. This is better than resolving each item individually.