Introduction
Nested resolver execution helps get related data step-by-step, like asking for a book and then its author details.
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)
}
};query {
books {
title
author {
name
}
}
}const resolvers = { Book: { author: (book) => { return fetchAuthorById(book.authorId); } } };
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
// }
// }
// }const resolvers = {
User: {
posts: (parent) => {
return posts.filter(post => post.userId === parent.id);
}
}
};User.posts return when called with parent = { id: 2 } if posts = [{id:1,userId:2},{id:2,userId:3},{id:3,userId:2}]?const resolvers = {
Author: {
books: (parent) => {
return books.filter(book => book.authorId = parent.id);
}
}
};Author and nested books resolver. How would you optimize nested resolver execution to avoid fetching all books for each author individually?Pass the test and this pattern moves unknown