To understand the concept of aliases in GraphQL we need to take a closer look at general query logic and identify what each part of a query is responsible for. All examples in this article can be found in this GitHub repository. If you also want to try these examples out in the GraphQL Playground tool, just clone the repository with
install dependencies with
and start the server in development with
To illustrate the aliases concept, let’s take this query for retrieving users from the database.
This query consists of different parts
- operation type "query": the type of action we want to do with the query. In GraphQL specification we have three different operation types -query, mutation and subscription.
- name "getUsers": name is important for debugging purposes.
- selection set "id", "firstName", "lastName", "phone", "username": this defines what data we would like to retrieve from the server.
There are also parts of the query which are called arguments, variables, fragments and directives. For simplicity’s sake we should leave that alone for now and return to them in future articles. When we execute this query with the proper server set-up (check outGithub repository), we should be able to retrieve the data.
You can see that the data are contained in the users field, which refers to the selected field in the query.
However, what happens if we want to query the users based on some argument? Let’s say that we have a schema for users, where the role argument is implemented and we want to query the users based on that role argument. Role arguments are used as a filter to retrieve the users. At first glance, the query can look like this:
This will return an error, because different data are stored in the same selection field. All results cannot be stored, as they have the same name and will be overwritten. For example, graphql-js will throw the error like this:
To resolve this issue we can use the aliases. The same query can be then rewritten with aliases like this
By executing this query we will retrieve the data filtered by the argument in the following format:
You can see that it is a much cleaner way to retrieve the data. We do not have to filter it on the frontend and we have it pre-filtered in the apollo store right away. This is not the best option every time, but it should be considered. When you use aliases, it is extremely important to keep in mind the performance and use of the data loader for batching requests to the database. Also it is appropriate in this case to use persisted queries, as the query is a bit bigger in size. This can be reduced with fragments.