Introduction

If you’re reading this article, then I assume you’re fairly convinced of the benefits GraphQL brings to the table. As you may have heard, GraphQL solves one of the fundamental problems of REST, which is the overfetching and underfetching of data.

These problems become even more apparent when you are building a server for mobile-first apps. In REST, there are two ways you can architect and design new requirements:

  • Create a new endpoint
  • Reuse an existing endpoint by fetching the extra information with it

Both approaches have their own set of tradeoffs: the first option will lead to more round trips, which is not ideal if the mobile user is in a spotty network condition; the second option wastes bandwidth unnecessarily.

We can solve both of these problems elegantly with GraphQL because it promises to give us exactly what we ask for. But if you don’t understand the quirks of GraphQL resolvers, you may run into overfetching problems even with GraphQL. Well-designed resolvers are fundamental to reaping the benefits of GraphQL.

A brief review of queries

In simple terms, resolvers are functions that resolve the value for a GraphQL type or a field of a GraphQL type. Before we jump into the resolver design process, however, let’s briefly look at the GraphQL query type.

What really makes GraphQL queries tick is the fact that they look like JSON, and everyone knows JSON well. For the sake of explanation, let’s design a GraphQL API for fetching data from a school database that has student and course information in the database.

Let’s say you’re writing a query that looks like:

query {
  student(id: "student1") {
    name,
    courses {
      title
    }
  }
}

Before this query hits the corresponding resolver, it is parsed into a tree/graph. As you might already know, a query is a root type. This means the query will be the root node of the tree, which looks something like this:

GraphQL Query Tree Diagram

As you can see, query is the root node, and student, name, courses, and title are the children. The GraphQL query is parsed into a tree like this before hitting the resolvers. It’s useful to visualize your queries this way because efficient resolvers are designed based on the actual structure of the queries.

#uncategorized #graphql

Avoid overfetching with properly designed GraphQL resolvers
1.10 GEEK