GraphQL 关联问题
GraphQL association issue
在深入研究代码之前,这里是对我的问题的高级解释:
在我的 GraphQL
架构中,我有两个根类型:Developers 和 Projects。我试图找到属于给定项目的所有开发人员。查询可能如下所示:
{
project(id:2) {
title
developers {
firstName
lastName
}
}
}
目前,我得到 开发人员 的 null
值。
虚拟数据
const developers = [
{
id: '1',
firstName: 'Brent',
lastName: 'Journeyman',
projectIds: ['1', '2']
},
{
id: '2',
firstName: 'Laura',
lastName: 'Peterson',
projectIds: ['2']
}
]
const projects = [
{
id: '1',
title: 'Experimental Drug Bonanza',
company: 'Pfizer',
duration: 20,
},
{
id: '2',
title: 'Terrible Coffee Holiday Sale',
company: 'Starbucks',
duration: 45,
}
]
因此,Brent 参与了这两个项目。劳拉从事第二个项目。我的问题出在 ProjectType
中的 resolve
函数中。我尝试了很多查询,但 none 似乎有效。
项目类型
const ProjectType = new GraphQLObjectType({
name: 'Project',
fields: () => ({
id: { type: GraphQLID },
title: { type: GraphQLString },
company: { type: GraphQLString },
duration: { type: GraphQLInt },
developers: {
type: GraphQLList(DeveloperType),
resolve(parent, args) {
///////////////////////
// HERE IS THE ISSUE //
//////////////////////
return _.find(developers, { id: ? });
}
}
})
})
开发者类型
const DeveloperType = new GraphQLObjectType({
name: 'Developer',
fields: () => ({
id: { type: GraphQLID },
firstName: { type: GraphQLString },
lastName: { type: GraphQLString }
})
})
所以你需要 return 所有开发人员在他们的 .projectIds
中有当前项目的 id
,对吗?
首先,_.find
无济于事,因为它 return 是第一个匹配的元素,您需要与开发人员一起获取数组(因为字段具有 GraphQLList
类型)。
那么
怎么样
resolve(parent, args) {
return developers.filter(
({projectIds}) => projectIds.indexOf(parent.id) !== -1
);
}
在深入研究代码之前,这里是对我的问题的高级解释:
在我的 GraphQL
架构中,我有两个根类型:Developers 和 Projects。我试图找到属于给定项目的所有开发人员。查询可能如下所示:
{
project(id:2) {
title
developers {
firstName
lastName
}
}
}
目前,我得到 开发人员 的 null
值。
虚拟数据
const developers = [
{
id: '1',
firstName: 'Brent',
lastName: 'Journeyman',
projectIds: ['1', '2']
},
{
id: '2',
firstName: 'Laura',
lastName: 'Peterson',
projectIds: ['2']
}
]
const projects = [
{
id: '1',
title: 'Experimental Drug Bonanza',
company: 'Pfizer',
duration: 20,
},
{
id: '2',
title: 'Terrible Coffee Holiday Sale',
company: 'Starbucks',
duration: 45,
}
]
因此,Brent 参与了这两个项目。劳拉从事第二个项目。我的问题出在 ProjectType
中的 resolve
函数中。我尝试了很多查询,但 none 似乎有效。
项目类型
const ProjectType = new GraphQLObjectType({
name: 'Project',
fields: () => ({
id: { type: GraphQLID },
title: { type: GraphQLString },
company: { type: GraphQLString },
duration: { type: GraphQLInt },
developers: {
type: GraphQLList(DeveloperType),
resolve(parent, args) {
///////////////////////
// HERE IS THE ISSUE //
//////////////////////
return _.find(developers, { id: ? });
}
}
})
})
开发者类型
const DeveloperType = new GraphQLObjectType({
name: 'Developer',
fields: () => ({
id: { type: GraphQLID },
firstName: { type: GraphQLString },
lastName: { type: GraphQLString }
})
})
所以你需要 return 所有开发人员在他们的 .projectIds
中有当前项目的 id
,对吗?
首先,_.find
无济于事,因为它 return 是第一个匹配的元素,您需要与开发人员一起获取数组(因为字段具有 GraphQLList
类型)。
那么
怎么样resolve(parent, args) {
return developers.filter(
({projectIds}) => projectIds.indexOf(parent.id) !== -1
);
}