Search code examples
graphqlapollostackapollo-server

How to create a nested resolver in apollo graphql server


Given the following apollo server graphql schema I wanted to break these down into separate modules so I don't want the author query under the root Query schema.. and want it separated. So i added another layer called authorQueries before adding it to the Root Query

type Author {
    id: Int,
    firstName: String,
    lastName: String
}  
type authorQueries {
    author(firstName: String, lastName: String): Author
}

type Query {
    authorQueries: authorQueries
}

schema {
    query: Query
}

I tried the following.. you can see that authorQueries was added as another layer before the author function is specified.

Query: {
    authorQueries :{
        author (root, args) {
            return {}
       }
    }
}

When querying in Graphiql, I also added that extra layer..

{
    authorQueries {
        author(firstName: "Stephen") {
            id
        }
    }
}

I get the following error.

"message": "Resolve function for \"Query.authorQueries\" returned undefined",


Solution

  • To create a "nested" resolver, simply define the resolver on the return type of the parent field. In this case, your authorQueries field returns the type authorQueries, so you can put your resolver there:

    {
      Query: { authorQueries: () => ({}) },
      authorQueries: {
        author(root, args) {
          return "Hello, world!";
        }
      }
    }
    

    So in the technical sense, there is no such thing as a nested resolver - every object type has a flat list of fields, and those fields have return types. The nesting of the GraphQL query is what makes the result nested.