0
0
GraphQLquery~5 mins

Resolver chains in GraphQL

Choose your learning style9 modes available
Introduction

Resolver chains help get data step-by-step in GraphQL. They let you break big tasks into smaller parts that work together.

When you want to get related data from different sources in order.
When one piece of data depends on the result of another.
When you want to keep your code simple by splitting complex queries.
When you want to reuse small resolver functions for different queries.
Syntax
GraphQL
type Query {
  firstData: FirstType
}

type FirstType {
  secondData: SecondType
}

type SecondType {
  value: String
}

// Resolver example
const resolvers = {
  Query: {
    firstData(parent, args, context) {
      // return first data
    }
  },
  FirstType: {
    secondData(parent, args, context) {
      // use parent to get second data
    }
  }
}

Resolvers are functions that get called to fetch data for each field.

Each resolver can use the result from the previous resolver via the parent argument.

Examples
This example shows a resolver chain where User.posts uses the user data from the parent resolver.
GraphQL
const resolvers = {
  Query: {
    user(parent, args) {
      return { id: 1, name: 'Alice' };
    }
  },
  User: {
    posts(parent, args) {
      // parent is user object
      return [{ id: 101, title: 'Hello' }];
    }
  }
};
Here, the Book.author resolver uses the book info from the parent to fetch the author.
GraphQL
const resolvers = {
  Query: {
    book(parent, args) {
      return { id: 5, title: 'GraphQL Guide' };
    }
  },
  Book: {
    author(parent, args) {
      // get author info using book id
      return { id: 2, name: 'Bob' };
    }
  }
};
Sample Program

This program sets up a GraphQL server with resolver chains. The User.posts resolver uses the user data to return posts.

GraphQL
const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    user: User
  }

  type User {
    id: ID
    name: String
    posts: [Post]
  }

  type Post {
    id: ID
    title: String
  }
`;

const resolvers = {
  Query: {
    user() {
      return { id: '1', name: 'Alice' };
    }
  },
  User: {
    posts(parent) {
      if (parent.id === '1') {
        return [
          { id: '101', title: 'Hello World' },
          { id: '102', title: 'GraphQL Rocks' }
        ];
      }
      return [];
    }
  }
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
OutputSuccess
Important Notes

Each resolver gets four arguments: parent, args, context, and info. The parent is key for chaining.

Resolver chains help keep your GraphQL API organized and efficient.

Summary

Resolver chains let you get data step-by-step using parent results.

They make complex queries easier by splitting work into small functions.

Use the parent argument to pass data between resolvers.