0
0
GraphQLquery~5 mins

Nested resolver execution in GraphQL

Choose your learning style9 modes available
Introduction
Nested resolver execution helps get related data step-by-step, like asking for a book and then its author details.
When you want to fetch a main item and its related details in one request.
When you need to show a list of items, each with extra information from another source.
When your data has layers, like orders with products inside each order.
When you want to keep your code organized by separating how each piece of data is fetched.
Syntax
GraphQL
type Query {
  books: [Book]
}

type Book {
  title: String
  author: Author
}

type Author {
  name: String
}

const resolvers = {
  Query: {
    books: () => fetchBooks()
  },
  Book: {
    author: (book) => fetchAuthorById(book.authorId)
  }
};
Resolvers for nested fields run only when those fields are requested in the query.
Each nested resolver receives the parent object to help fetch related data.
Examples
This query asks for each book's title and the name of its author.
GraphQL
query {
  books {
    title
    author {
      name
    }
  }
}
This resolver fetches the author details for each book using the book's authorId.
GraphQL
const resolvers = {
  Book: {
    author: (book) => {
      return fetchAuthorById(book.authorId);
    }
  }
};
Sample Program
This example shows books with their authors. The nested resolver for author finds the matching author by ID.
GraphQL
type Query {
  books: [Book]
}

type Book {
  title: String
  author: Author
}

type Author {
  name: String
}

const booksData = [
  { id: 1, title: "The Sun", authorId: 101 },
  { id: 2, title: "Moonlight", authorId: 102 }
];

const authorsData = [
  { id: 101, name: "Alice" },
  { id: 102, name: "Bob" }
];

const resolvers = {
  Query: {
    books: () => booksData
  },
  Book: {
    author: (book) => authorsData.find(a => a.id === book.authorId)
  }
};

// Sample query
// {
//   books {
//     title
//     author {
//       name
//     }
//   }
// }
OutputSuccess
Important Notes
Nested resolvers run only if the nested field is requested in the query.
The parent object passed to a nested resolver contains the data fetched by the parent resolver.
Keep nested resolvers simple to avoid slow queries.
Summary
Nested resolver execution lets you fetch related data step-by-step.
Each nested resolver gets the parent data to find its related info.
Use nested resolvers to keep your GraphQL queries organized and efficient.