Given a GraphQL schema with types Book and Author, and a search query that returns a union of these types, what will be the result of this query?
query {
search(text: "Alice") {
__typename
... on Book {
title
pages
}
... on Author {
name
booksWritten
}
}
}Remember that the search query returns a union type, so you need to check the __typename to know which fields are available.
The query returns both Author and Book objects matching the text "Alice". The __typename field tells us which type each result is, so the output includes both types with their respective fields.
In GraphQL, how can you write a query that searches across different types like Movie and Director and returns results from both?
Think about how to combine different types into one result list.
Union types let you combine multiple object types into one field. Inline fragments in the query let you specify fields for each type.
What is wrong with this GraphQL query that searches across Article and Author types?
query {
search(text: "GraphQL") {
... on Article {
title
content
}
... on Author
name
articlesCount
}
}Check the syntax of inline fragments carefully.
Inline fragments require curly braces around the fields. The Author fragment is missing these braces, causing a syntax error.
You have a search query returning a union of Product and Category. How can you reduce the amount of data sent over the network?
Think about selecting only necessary data.
GraphQL lets you specify exactly which fields you want. Using inline fragments to request only needed fields reduces data size.
Given this query:
query {
search(text: "John") {
__typename
... on User {
username
}
... on Post {
title
}
}
}But the result is always an empty list, even though there are users and posts with "John" in their data. What is the most likely cause?
Think about what the backend resolver does with the search argument.
If the search resolver only searches one type or is not implemented for both types, the query returns no results even if data exists.