If you use GraphQL in your production application, you may have encountered a situation where you need your custom query to return custom field names. Or, perhaps you received two query results in the same server response, causing field names to clash.

In these cases, we can use the GraphQL alias to improve our query. In this tutorial, we’ll look at what an alias is, how it works, and when you should use it. We will examine several cases and extend this concept with a related example. Let’s get started!

What is a GraphQL alias?

Aliases allow us to rename the data returned in the query results. Aliases do not change the original schema; instead, they manipulate the structure of the query result retrieved from the database, displaying it according to your specification.

Aliases come in handy when you want to improve your query efficiency. For example, suppose you try to get the same data by applying various filters. Many developers will prefer to write separate queries and execute them in separate API calls. In this and other cases, aliases can help you optimize and improve your query organization.

There are several situations where you might want to change the name of the field from which you receive query results. Let’s look at two different examples.

Get multiple objects in a single query

Using aliases, you can combine multiple fetches of the same object in a single GraphQL query.

Let’s say you’re building an application that displays a list of posts in a feed. In your application, a typical post would look like the following code block.

type Post {
  id: string
  parent: string
  type: string # POST or COMMENT
  author: string
  title: string
  text: string
  createdAt: string
}
Copy the code

For simplicity, we limit ourselves to the string data type for each field. Ideally, you would use an enumeration for the Type field and a custom date scalar for the createdAt field.

Notice that we define a Type field to accommodate different types of posts in the same table. In our case, we have posts and comments.

The query for getPosts looks like the following code block.

query getPosts {
  posts {
    id
    parent
    type
    author
    title
    text
    createdAt
  }
}
Copy the code

Now, let’s say you have a post and a comment in your database. If you run the query above, you get a response similar to the code block below.

{
  "data": {
    "posts": [
      {
        "id": "s9d8fhsd-fsdf",
        "parent": null,
        "type": "POST",
        "author": "Korg",
        "title": "Let's start a revolution",
        "text": "Hey, man. I'm Korg. We're gonna get outta here on that big spaceship. Wanna come?",
        "createdAt": "11:06 AM IST, Aug 7 2021"
      },
      {
        "id": "d8g6dffd-jfod",
        "parent": "s9d8fhsd-fsdf",
        "type": "COMMENT",
        "author": "Loki",
        "title": null,
        "text": "Well, it seems that you are in dire need of leadership.",
        "createdAt": "11:09 AM IST, Aug 7 2021"
      }
    ]
  }
}
Copy the code

Your database may also contain a long list of posts and comments, as in the example above. You might try writing a query to get the posts in a separate list of posts and comments.

query getPosts {
  posts(type: "POST") {
    id
    author
    title
    text
    createdAt
  }
  posts(type: "COMMENT") {
    id
    parent
    author
    text
    createdAt
  }
}
Copy the code

However, you will find that the query does not run at all, and it throws the following error.

{
  "errors": [
    {
      "message": "Fields 'posts' conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.",
      "locations": [
        {
          "line": 2,
          "column": 3
        },
        {
          "line": 9,
          "column": 3
        }
      ]
    }
  ]
}
Copy the code

When executed, the query returns two result lists of posts for the same field name. Using aliases, we can change the field names to two different keywords and make the query run perfectly.

query getPosts {
  posts: posts(type: "POST") {
    id
    author
    title
    text
    createdAt
  }
  comments: posts(type: "COMMENT") {
    id
    parent
    author
    text
    createdAt
  }
}
Copy the code

Now you can easily make multiple fetch calls within the same GraphQL query, saving network usage and reducing code complexity.

Add meaning to your query results

A self-explanatory name makes it easy for any developer to understand your code. The same is true for database results. You need to make sure that the developer handling the API response knows what the data means. Let’s learn how to add meaning to our query results to help provide useful naming conventions.

Let’s reconsider our previous example. Our pattern looks like the following code block.

type Post {
  id: string
  type: string # POST or COMMENT
  author: string
  title: string
  text: string
  createdAt: string
}
Copy the code

This pattern contains a parent field that is designed to relate a comment to a post, defining which post is the parent of the comment. While this should make sense to database engineers, it may not be immediately obvious to front-end engineers.

In this case, you can construct your traditional query to better describe the parent properties.

query getPosts {
  posts {
    id
    parentPost: parent
    type
    author
    title
    text
    createdAt
  }
}
Copy the code

You can rename other attributes as you wish. The original name is completely overwritten in the results returned after the query is executed. A typical response would look like the following code block.

{
  "data": {
    "posts": [
      {
        "id": "s9d8fhsd-fsdf",
        "parentPost": null,
        "type": "POST",
        "author": "Korg",
        "title": "Let's start a revolution",
        "text": "Hey, man. I'm Korg. We're gonna get outta here on that big spaceship. Wanna come?",
        "createdAt": "11:06 AM IST, Aug 7 2021"
      },
      {
        "id": "d8g6dffd-jfod",
        "parentPost": "s9d8fhsd-fsdf",
        "type": "COMMENT",
        "author": "Loki",
        "title": null,
        "text": "Well, it seems that you are in dire need of leadership.",
        "createdAt": "11:09 AM IST, Aug 7 2021"
      }
    ]
  }
}
Copy the code

Best practices for GraphQL aliases

While implementing aliases in GraphQL is fairly straightforward, improper use can wreak havoc on your application. To optimize the results of the GraphQL alias, it’s important to keep the following points in mind.

Self-explanatory naming

Because aliases allow you to change the field names of your results, you must make sure that the names you choose make sense for the actual data.

While it is tempting to choose a name that is convenient, short and easy for you to understand, you must also consider that other developers may be working on the project after you. Unless your naming conventions are self-explanatory, they may have a hard time understanding your code and could cause errors in your project.

For example, the following code contains an example of a misnamed alias.

query getPosts {
  p: posts(type: "POST") {
    id
    author
    title
    text
    createdAt
  }
  c: posts(type: "COMMENT") {
    id
    parent
    author
    text
    createdAt
  }
}
Copy the code

It might seem convenient to name the two intermediate query results P for the post and c for the comment, but let’s look at the results of the above query.

{
  "data": {
    "p": [
      {
        "id": "s9d8fhsd-fsdf",
        "author": "Korg",
        "title": "Let's start a revolution",
        "text": "Hey, man. I'm Korg. We're gonna get outta here on that big spaceship. Wanna come?",
        "createdAt": "11:06 AM IST, Aug 7 2021"
      },
    ],
    "c": [
      {
        "id": "d8g6dffd-jfod",
        "parent": "s9d8fhsd-fsdf",
        "author": "Loki",
        "text": "Well, it seems that you are in dire need of leadership.",
        "createdAt": "11:09 AM IST, Aug 7 2021"
      }
    ]
  }
}
Copy the code

As you can see, it is difficult to understand what P and C mean without contextual information about the type of result. So, in this case, sticking with posts and Comments in their full names would be a better choice.

Use aliases only when needed

Aliases are just pseudonyms for an existing field, so you might want to use them even if you don’t necessarily need them. However, renaming can lead to unnecessary mappings in your code. For example, let’s take our getPosts query.

query getPosts {
  posts {
    id
    parent
    type
    author
    title
    text
    createdAt
  }
}
Copy the code

Each field in the Posts definition is self-explanatory. However, you may want to add a more powerful descriptor for each field, as shown below.

query getPosts {
  posts {
    postId: id
    parentPost: parent
    postType: type
    author
    title
    postContent: text
    createdAt
  }
}
Copy the code

Keep in mind that you need to propagate the new name in your code every time you rename it. Before adding an alias, you should consider whether the extra details are useful. I recommend using aliases only if you have solved a recurring problem.

Modify the server side

If you find yourself renaming the same field repeatedly, you may want to consider abandoning the alias and renaming the field on the server itself. Also, if you have to use aliases frequently in your client, you may need to reduce your database schema.

Aliases are meant to facilitate quick renaming, however, you should not rely heavily on them. If you find yourself using aliases a lot, your server-side naming conventions may be problematic. In this case, using aliases only complicates the code base.

conclusion

Aliases are a great way to reorganize GraphQL query results. Aliases are especially useful when your back-end data model and front-end data specifications do not match up perfectly and you need to adjust them manually.

Aliases are necessary when you need to fetch multiple query results from the same source at once. However, it is also necessary to use fewer aliases. Although aliases are mostly harmless and only change when the data is returned, their unnecessary use can cause confusion in the data schema and even lead to errors.

I hope you enjoyed this tutorial

Using aliases in GraphQL first appeared on the LogRocket blog.