Given the graphql union type
union SearchResult = Human | Droid | Starship
and the following graphql query:
{
search(text: "an") {
... on Human {
... on SearchResult {
... on Droid {
appearsIn
}
}
}
}
}
Why is it in graphql syntactically correct to go from a "sub type" inline fragment (Human
) to a "super type" inline fragment (SearchResult
) and back to another "sub type" inline fragment (Droid
)? Are there any use cases for this?
For me this really does not make sense and it should throw an error. It leads to dead query parts like the Droid
inline fragment above that has no effect on the query result.
Without this rule, named and inline fragments can behave the same way, and this can make sense if you have more involved "get generic bits" fragments for interface or union types. If you split out the query this way:
fragment SearchResultBits on SearchResult {
...on Droid { appearsIn }
# could have parts for other union choices too
}
query DoSearch($text: String!) {
search(text: $text) { ... SearchResultBits }
}
Then on your query it's very sensible to reuse the (named) SearchResultBits
query FromQuestion {
search(text: "an") {
... on Human {
name
... SearchResultBits
}
# or return nothing for non-humans
}
}
Since the named fragment reference and the inline fragment both behave the same way, you'll get the same result here. It seems more reasonable for this named fragment reference to be legal and so there doesn't seem to be a strong reason to forbid the equivalent inline fragment either.