Having to define new fragments to retrieve fields of concrete types can be a little unwieldy. To make things simpler, you can create inline fragments which are defined and used within the query itself.
To do this, use the spread operator and define the fragment at point of use, omitting the word fragment
and its name. So this:
{
node(id: "3") {
id
...nameFields
}
}
fragment nameFields on Person {
firstName
}
…becomes this:
{
node(id: "3") {
id
...on Person {
firstName
}
}
}
-
Using inline fragments, retrieve the fields for the two different concrete types we used earlier, the
node
s with the following IDs:"MDQ6VXNlcjU3MjQzNw=="
"MDEyOk9yZ2FuaXphdGlvbjkxMzU2Nw=="
-
You can think of the
...on Person
as a "type condition". If aPerson
is returned, its fields (egfirstName
) will be retrieved. So you can select the fields you want based on the runtime type, kind of like a declarativeif
statement: if aPerson
is returned, get me theirfirstName
. -
If the fields in the inline fragment are of the same type as the enclosing context, you can omit the
on MyType
. What does this query return?{ location(id: 4) { name address ... { city country } } }
This may not seem that useful, but its use will become clear in the next module.