让我们假设在 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
}
}
从上面的例子可以看出,有id的好友都存储在数据库中。
如何编写一个解析器,通过发送单个 graphql 请求同时获取用户详细信息(通过 id)以及所有用户 friend 的详细信息?
最佳答案
解析器采用四个参数(obj、args、ctx、info)
。
第一个参数,在本例中,obj
具有来自父对象的解析器的结果(UserType 的父解析器)。因此,如果您在friends字段的解析器中执行obj.friends
,您将得到正确的结果。
示例:
friends: {
type: new GraphQLList(GraphQLString),
resolve: (obj) => {
return obj.friends
}
}
关于node.js - GraphQL:graphql 中嵌套对象类型的解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47118530/