Working with GraphQL aliases
This article will go through a use-case where having aliases can be very useful in the GraphQL query. I have been working on a graphQL project for over a month now and recently came across the need of using aliases and thought of sharing it.
A query in GraphQL has different components such as arguments, directives, fields and fragments. Let’s say we have a scenario where we want to get the data on an object type but with different arguments in the same query. For example, we have a schema in which an Employee can be a Manager or Engineer. The below query would run perfectly fine for the above use-case.
Let say we have to get all the employees based on their positions. In this case we could query the server passing the position as an argument to the query. This filters data on position of the employee and gets you the results based on the filters within a single query. Let’s look at the query below.
The above would return an error because GraphQL expects different field name. Due to the conflicting behavior of the field names cannot differentiate between objects as two separate fields. We can resolve this by using aliases and still get the results in a single query. The query below shows how to define aliases in a query.
The above query would resolve the conflict as now the field names are different and returns an array which looks something like below.