GraphQL:graphql中嵌套对象类型的解析器

时间:2017-11-05 05:35:36

标签: node.js graphql

让我们假设在graphql架构中,存在一个UserType对象:

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

数据库中存在以下数据:

{
   "Users":[
       {
         "id": "1",
         "name": "John Doe",
         "email": "John@gmail.com",
         "age": 35,
         "friends": [
             "3",
             "5",
             "7"   
          ]

       }
   ]
} 

查询:

user {
   name
   friends {
      name
   }
}

从上面的例子中可以看出,有ids的朋友存储在数据库中。

如何通过发送单个graphql请求来编写解析器以获取用户详细信息(通过id)以及所有用户朋友的详细信息?

1 个答案:

答案 0 :(得分:1)

解析器采用四个参数(obj, args, ctx, info)。 在这种情况下,第一个参数obj具有来自父对象(用户类型的父解析器)的解析器的结果。因此,如果您在“朋友”字段的解析器中进行obj.friends,则将获得正确的结果。

示例:

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