GraphQL - Inline Fragments
Integrations GraphQL Training Xurrent GraphQL Inline Fragments

GraphQL - Inline Fragments

The __typename field

When we introduced Types in the topic Building a Simple GraphQL Query of this training, we explained that in GraphQL a type is defined for all objects (and that the branches in your Selection Set always need to end on a field of one of the basic types ).
It is possble to check the type of a field in a GraphQL query with the special field __typename.

This can be interesting when you don’t know in advance the type of the object. For example a Translation can be linked to multiple record types: a service, a service instance, a knowledger article, a UI Extension, etc. For a given Translation this is specified in the field owner.

Exercise:

Don’t forget to specify the widget account in the header and to add Translations as a record type to the scope of the personal access token. In Insomnia, this query looks like:
Query the __typename of the owner of a Translation
In the response you will find the different record types that have been translated:
The owner of Translations according to the __typename

Inline Fragments

In case a field can return different types, the available fields on the object in the response will be different depending on the type. In the example of Translations, when the owner is a Service, the field serviceOwner is available, in case of a Knowledge Article the field instructions is relevant. You cannot specify these fields in the Selection Set for owner: these are only valid for the given type.

That’s where Inline Fragments come into play. You have learned in the previous topic how to define a fragment with this syntax fragment fragmentName on Object{fields} and how to use the fragment in the Query with the syntax ...fragmentName.
An Inline Fragment has the following syntax ...on Type and can be used in a query to specify for a field for which you don’t know the type upfront, the Solution Set given the field is of the given type. In the example of the owner of a Translation you are able to specify the following Inline Fragments:
owner {
...on Service {
serviceOwner
}
...on KnowledgeArticle {
instructions
}
}

Another example where you do not know in advance which type you will receive is for the assignment field in a Time Entry: a time entry can be linked to a problem, a project task, a request, a task or to no record at all.

Exercise:

Don’t forget to specify the widget account in the header and to add time entries as a record type to the scope of the personal access token. In Insomnia, this query looks like:
Query time entries with an inline fragment

Next Topic