Search code examples
graphqlgraphql-jsapollo-serverexpress-graphqlgraphql-tools

Write resolvers for nested type definitions


Suppose I have following type definition for my GraphQL API:

const typeDef = `
    type Book {
         title: String
         author: Author
         likes: Int
    }

    type Author {
         id: String
         name: String
         age: Int
         books: [Book]
    }

    type Query{
         books(authorid: String!): Book
    }
`

Then, how many resolvers do I need for this? Should I handle this query request with only one resolver books and return all books and author info or should I make many resolvers such as Query -> books, Book -> author and Author -> books? I am not sure how the modular schema and resolver works together.


Solution

  • No matter how many type(Book, Author etc) or input you use you need to provide .

    const schema = ` 
        type Mutation {
            mutatePost(postId:Int) :Int
        }
        type Query {
            hello: String
            posts: [String]
            books(authorId: String!): Book
        }
      `
    

    You need to use same name as you defined in Query must be same in resolver

       const resolvers = {
            Query: {
            async hello() {
                return 'Hello';
            },
            async posts() {
                return ['Hello', 'World];
            },
            async books(_, { authorId }) {
                //Return data which you is defined in type Book
                //return Book
            }
            },
            Mutation: {
                async mutatePost(_, {
                postId
                }, context) {
                //return Integer
                }
            },
        }
    

    Only thing every Query and Mutation need queryResolver and mutationResolver