Xurrent GraphQL - Aliases and Fragments
Aliases
In the previous exercises you have learned how to add filters to GraphQL queries. Imagine now that your integration needs to process requests and that the logic to process requests of category Incident is different from the logic to process requests of category RFC. Of course, you could create two queries or you could filter the list of requests in your integration script. But what if GraphQL could return you both lists with just one query?
This is possible with Aliases. Let’s have a look at the following simple example: the GraphQL query hereunder will list the number of people with ‘Andy’ and with ‘John’ in the name. Two aliases have been designed: ‘john’ and ‘andy’. In the data of the response a section for each alias can be found.
In the following exercise, you will use Aliases to get a list of Incidents and a list of RFCs.
Exercise:
Create a GraphQL query to get the first two requests of category incident
and the first two requests of category rfc
. Get the subject, and the name of the requested for person for all the requests. For an incident, list the impact. For an rfc list the subject of the template.
Don’t forget to add read rights on the person, request and request template record types to the scope of the personal access token.
In Insomnia, this query looks like:
Check how the results are bundled according to the 2 aliases ‘getincidents’ and ‘getrfcs’:
Fragments
In the previous exercise for both the requests of category incident and of category rfc, you had to specify the fields subject
and requestedFor
in the Selection Set. You can avoid this overhead of typing exactly the same part twice by specifying that part of the Selection Set in a Fragment.
Going back to the example to query all people called ‘Andy’ and ‘John’. Imagine that I want for each of them the full name, the job title, the language and the primary email address. This could be done by defining a fragment, syntax fragment fragmentName on Object{fields}
. Once the fragment has been defined, it can be used in a query with ...fragmentName
.
In Insomnia this query based on a Fragment will become:
Exercise:
Use a Fragment in the GraphQL query you have created in the previous exercise to get the subject and the name of the requested for person of the incidents and of the RFCs.
In Insomnia, this query looks like: