4me GraphQL - Aliases and Fragments
Integrations GraphQL Training GraphQL Aliases and Fragments

4me 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.

Use Aliases for people records

In the following exercise, you will use Aliases to get a list of Incidents and a list of RFCs.

Exercise:

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:
Use Aliases for a query on requests


Check how the results are bundled according to the 2 aliases ‘getincidents’ and ‘getrfcs’:
Results when using Aliases for a query on requests


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:

Use a fragment for a query on people records

Exercise:

In Insomnia, this query looks like:Use a fragment for a query on requests

Next Exercise