0
0
GraphQLquery~30 mins

Resolver organization in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Organizing GraphQL Resolvers for a Bookstore
📖 Scenario: You are building a simple GraphQL API for a bookstore. The API needs to provide information about books and authors.To keep your code clean and easy to maintain, you want to organize your GraphQL resolvers properly.
🎯 Goal: Build a well-organized set of GraphQL resolvers separated by type (Query, Book, Author) to fetch book and author data.
📋 What You'll Learn
Create a books array with 3 books, each having id, title, and authorId
Create an authors array with 2 authors, each having id and name
Create a resolvers object with three keys: Query, Book, and Author
In Query, add a resolver books that returns the books array
In Book, add a resolver author that returns the author object matching the book's authorId
In Author, add a resolver books that returns all books written by that author
💡 Why This Matters
🌍 Real World
Organizing resolvers by type is a common practice in real GraphQL APIs to keep code modular and easy to understand.
💼 Career
Understanding resolver organization is essential for backend developers working with GraphQL to build scalable and maintainable APIs.
Progress0 / 4 steps
1
Create the initial data arrays
Create an array called books with these exact objects: { id: '1', title: '1984', authorId: 'a1' }, { id: '2', title: 'Animal Farm', authorId: 'a1' }, and { id: '3', title: 'Brave New World', authorId: 'a2' }. Also create an array called authors with these exact objects: { id: 'a1', name: 'George Orwell' } and { id: 'a2', name: 'Aldous Huxley' }.
GraphQL
Hint

Use const books = [...] and const authors = [...] to create the arrays with the exact objects.

2
Create the resolver object with Query type
Create a resolvers object. Inside it, add a Query object with a resolver function books that returns the books array.
GraphQL
Hint

Inside resolvers, add Query: { books: () => books } to return the books array.

3
Add the Book type resolver for author
Inside the resolvers object, add a Book object. Add a resolver function author that takes book as an argument and returns the author object from authors whose id matches book.authorId.
GraphQL
Hint

Use Book: { author: (book) => authors.find(author => author.id === book.authorId) } inside resolvers.

4
Add the Author type resolver for books
Inside the resolvers object, add an Author object. Add a resolver function books that takes author as an argument and returns an array of books from books whose authorId matches author.id.
GraphQL
Hint

Use Author: { books: (author) => books.filter(book => book.authorId === author.id) } inside resolvers.