Learn GraphQL · 7/15

Resolvers: The Engine Under the Hood

6 min read

Resolvers: The Engine Under the Hood ⚙️

Welcome back! So far, you've been designing the "what" of your API with schemas. Now, it's time to dive into the "how." How does your GraphQL server actually fetch the data for the fields a client requests? The answer lies in resolvers.

Think of your GraphQL schema as a menu at a restaurant. It lists all the delicious dishes (data) a customer (client) can order. Resolvers are like the chefs in the kitchen who know the recipe and how to prepare each dish. For every field in your schema, there's a corresponding resolver function responsible for returning the data for that field.

In essence, resolvers are the functions that do the heavy lifting of fetching data from a database, a third-party API, or any other source. They are the bridge between your schema's structure and your data sources.


1. Resolver Signatures: Parent, Args, Context, and Info

Every resolver function in GraphQL receives four arguments. Understanding these is crucial to harnessing their full power. Let's break them down one by one.

The signature of a resolver function typically looks like this:

javascript
fieldName(parent, args, context, info) {
  // ... your logic to fetch and return data
}

Imagine you're a librarian. A person comes to you with a request for a book.

  • parent (or obj or root): This is like knowing the section of the library the person is currently in. For top-level queries, this is often not used. However, for nested fields, it contains the result of the parent field's resolver. This is how you access data from the "parent" object to resolve its "child" fields.
  • args: These are the specific instructions the person gives you, like "I want the book with the title 'The Hitchhiker's Guide to the Galaxy'." The args object contains the arguments passed to the field in the GraphQL query.
  • context: This is your librarian's toolkit—your computer with access to the library's database, your knowledge of where everything is, and your security clearance to access restricted sections. The context is an object shared across all resolvers for a single request. It's perfect for holding per-request state like authentication information, database connections, or data loaders.
  • info: This contains detailed information about the query's execution state, including the field name and the path to the field from the root. Think of this as the complete request slip with all the nitty-gritty details. You'll rarely need to use this, but it's there for advanced use cases like query optimization.

Here's a quick example:

javascript
// Schema
type Query {
  user(id: ID!): User
}

type User {
  id: ID!
  name: String
}
javascript
// Resolvers
const resolvers = {
  Query: {
    user: (parent, args, context, info) => {
      // args will be { id: "some-id" }
      // You can use context to access a database connection
      return context.db.users.find(user => user.id === args.id);
    },
  },
};

2. Fetching Top-Level Data in Root Resolvers

The entry points to your GraphQL API are the fields on the Query, Mutation, and Subscription types. These are often called "root fields," and their corresponding resolvers are "root resolvers." These are the resolvers that kick off the data fetching process.

Let's say you have a query to get all books:

graphql
type Query {
  books: [Book]
}

type Book {
  title: String
  author: String
}

The resolver for the books field would be responsible for fetching all the books from your data source.

javascript
const resolvers = {
  Query: {
    books: (parent, args, context) => {
      // In a real application, you would fetch this from a database
      return [
        { title: 'The Lord of the Rings', author: 'J.R.R. Tolkien' },
        { title: 'The Hobbit', author: 'J.R.R. Tolkien' },
      ];
    },
  },
};

Since fetching data from a database is often an asynchronous operation, resolvers can return Promises (or use async/await). GraphQL will wait for the promise to resolve before continuing.

javascript
const resolvers = {
  Query: {
    books: async (parent, args, context) => {
      // Assuming context.db is a database connection
      return await context.db.collection('books').find().toArray();
    },
  },
};

Fun Fact: If you don't provide a resolver for a field, GraphQL.js will often try to find a property with the same name on the parent object. This is called the default resolver.


3. Resolving Nested Objects and Relational Data

The real power of GraphQL shines when you have nested data. Imagine you want to fetch a book and its author's information.

graphql
type Query {
  book(id: ID!): Book
}

type Book {
  id: ID!
  title: String
  author: Author
}

type Author {
  id: ID!
  name: String
}

When a query asks for a book's author, GraphQL will first execute the book resolver. Once that resolves and returns a book object, it will then execute the author resolver on the Book type. The key here is the parent argument.

javascript
const resolvers = {
  Query: {
    book: async (parent, { id }, context) => {
      return await context.db.collection('books').findOne({ _id: id });
    },
  },
  Book: {
    author: async (parent, args, context) => {
      // The 'parent' argument here is the book object returned from the 'book' resolver
      const book = parent;
      return await context.db.collection('authors').findOne({ _id: book.authorId });
    },
  },
};

This chain of resolvers allows GraphQL to efficiently fetch related data.


4. The Context Object: Passing Shared State and Auth 🕵️‍♀️

As mentioned earlier, the context object is a shared space for all resolvers in a single request. This is incredibly useful for things that you need in multiple places, but don't want to pass around manually.

Problem: How do you handle user authentication? How do you give your resolvers access to your database connection without creating a new one for every resolver?

Solution: The context object!

When you set up your GraphQL server, you can create a context function that gets called for every incoming request. This function can return an object with any data you want to be available to all your resolvers.

A common use case is to verify a user's token and add their user object to the context.

javascript
// In your server setup (e.g., with Apollo Server)
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: async ({ req }) => {
    // Get the user token from the headers
    const token = req.headers.authorization || '';

    // Try to retrieve a user with the token
    const user = await getUser(token);

    // Add the user to the context
    return { user };
  },
});

Now, any resolver can check if a user is authenticated:

javascript
const resolvers = {
  Query: {
    me: (parent, args, context) => {
      // If the user isn't logged in, context.user will be null
      if (!context.user) {
        throw new Error('You are not authenticated!');
      }
      return context.user;
    },
  },
};

This keeps your resolvers clean and focused on their specific data-fetching logic, while centralizing common concerns like authentication.


📚 Further Reading:

Challenge

You are building the resolver logic for a GraphQL API. A schema and a mock database object are provided. Your task is to implement the resolvers object to correctly fetch data according to the schema.

The mock database will be available on the context object at context.db.

Requirements:

  1. Query.user resolver: This resolver should accept an id from the args object and find the corresponding user in the context.db.users array.
  2. User.posts resolver: This is a nested resolver. It should use the parent object (which will be a User object) to find all posts in context.db.posts written by that user. Use the user's id for filtering.
  3. Post.comments resolver: This is another nested resolver. It should use the parent object (which will be a Post object) to find all comments in context.db.comments that belong to that post. Use the post's id for filtering.

Expected result

Your code should be a complete JavaScript resolvers object that correctly implements the three specified functions.

  • The Query.user function should return a single user object from context.db.users that matches the args.id.
  • The User.posts function should return an array of post objects from context.db.posts where the authorId matches the parent.id.
  • The Post.comments function should return an array of comment objects from context.db.comments where the postId matches the parent.id.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.