vrn
vrn

Reputation: 159

GraphQL: Resolver for nested object types in graphql

Lets assume in the graphql schema, a UserType object is present:

const UserType = new GraphQLObjectType({
    name:'User',
    fields:() => ({
        id: {type:GraphQLString},
        name: {type: GraphQLString},
        email: {type: GraphQLString},
        age: {type: GraphQLInt},
        friends: {type: new GraphQLList(UserType)}
    });
});

The following data is present in the database:

{
   "Users":[
       {
         "id": "1",
         "name": "John Doe",
         "email": "[email protected]",
         "age": 35,
         "friends": [
             "3",
             "5",
             "7"   
          ]

       }
   ]
} 

Query:

user {
   name
   friends {
      name
   }
}

As can be seen in the above example, the friends with ids are stored in the database.

How do I go about writing a resolver to get the user details (by id) plus details of all the users friends at the same time by sending a single graphql request?

Upvotes: 1

Views: 1402

Answers (1)

thishandp7
thishandp7

Reputation: 182

The resolver takes four arguments (obj, args, ctx, info). The first argument, in this case, obj has the result of the resolver from the parent's object (The parent resolver to the UserType). Therefore if you do obj.friends in the friends field's resolver, you will get the correct result.

Example:

friends: {
  type: new GraphQLList(GraphQLString),
  resolve: (obj) => {
    return obj.friends
  }
}

Upvotes: 1

Related Questions