您可以使用对象类型的本地解析来做到这一点。
在子节点的解析中,可以访问整个父节点数据。例如:
export const User: GraphQLObjectType = new GraphQLObjectType({
name: 'User',
description: 'User type',
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLID),
description: 'The user id.',
},
name: {
type: new GraphQLNonNull(GraphQLString),
description: 'The user name.',
},
friends: {
type: new GraphQLList(User),
description: 'User friends',
resolve: (source: any, args: any, context: any, info: any) => {
console.log('friends source: ', source)
return [
{id: 1, name: "friend1"},
{id: 2, name: "friend2"},
]
}
}
}),
})
const Query = new GraphQLObjectType({
name: 'Query',
description: 'Root Query',
fields: () => ({
user: {
type: User,
description: User.description,
args: {
id: {
type: GraphQLInt,
description: 'the user id',
}
},
resolve: (source: any, args: any, context: any, info: any) => {
console.log('user args: ', args)
return { id: 2, name: "user2" }
}
}
})
})
在friends
解析中,source
参数具有来自父user
解析的全部返回值。所以在这里我可以根据我得到的用户 ID 来获取所有的朋友source
。
希望能帮助到你。