GraphQL / Resolvers in GraphQL

Working with Parent and Context Data

This tutorial will guide you through working with parent and context data in GraphQL. These concepts are essential for structuring your resolver functions.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers how to write and manage resolver functions in GraphQL.

Introduction

This tutorial is aimed at helping you understand how to work with parent and context data in GraphQL. By the end of this tutorial, you will be able to:

  • Understand what parent and context data are in GraphQL
  • Know how to use parent and context data in your resolver functions

Prerequisites:

  • Basic understanding of JavaScript
  • Familiarity with GraphQL and its syntax

Step-by-Step Guide

In GraphQL, each field on each type is backed by a function called the resolver which returns the value for that field. The resolver function in GraphQL receives four arguments:

  • parent: This is the result of the parent resolver execution. This argument is useful when the field's value is a nested field within the parent value.
  • args: The arguments provided for the field in the GraphQL query.
  • context: This is an object that gets passed through the resolver chain and is useful for passing essential backend resources, such as a database connection.
  • info: Contains information about the execution state of the query.

In this tutorial, we will focus on parent and context.

Parent

When a resolver is run, it uses the parent argument to fetch the data that the client is asking for. The parent argument represents the result returned from the resolver for the parent field, essentially the object that contains the current field.

Context

The context argument is a value that is provided to every resolver and holds important contextual information like the currently logged in user, database connection, etc.

Code Examples

Let's look at a simple example of using parent and context in a resolver.

const resolvers = {
  Query: {
    user: (parent, args, context, info) => {
      // Use context to access the database
      return context.db.loadUserByID(args.id);
    },
  },
  User: {
    posts: (parent, args, context, info) => {
      // Use parent to access the user that was returned in the parent resolver
      return context.db.loadPostsByUserID(parent.id);
    },
  },
};

In this example, we have two resolvers. The user resolver accesses the database from the context to fetch a user by their ID. The posts resolver then uses the parent argument to access the user object that was returned from the user resolver. It fetches the posts for this user from the database.

Summary

In this tutorial, we've learned about the parent and context arguments in GraphQL resolvers. We've learned that parent represents the result returned from the resolver for the parent field, and context is a value that holds important contextual information.

To further your understanding, you can:

  • Try creating more complex resolver chains and see how the parent argument changes
  • Experiment with different things you can pass in the context

Practice Exercises

  1. Exercise: Create a resolver chain for a Blog -> Author -> Comments schema.

Solution:

const resolvers = {
  Blog: {
    author: (parent, args, context, info) => {
      return context.db.loadAuthorByID(parent.authorId);
    },
  },
  Author: {
    comments: (parent, args, context, info) => {
      return context.db.loadCommentsByAuthorID(parent.id);
    },
  },
};
  1. Exercise: Create a resolver for a Post field that uses the context to check if a user is authenticated before returning the post.

Solution:

const resolvers = {
  Post: {
    post: (parent, args, context, info) => {
      if (!context.user.isAuthenticated) {
        throw new Error('Not authenticated');
      }
      return context.db.loadPostByID(args.id);
    },
  },
};

In the solution, we use the context to check if a user is authenticated. If they are not, we throw an error. If they are, we access the database from the context to fetch the post.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Favicon Generator

Create favicons from images.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help