GraphQL关联问题
在深入研究代码之前,以下是对我的问题的高级解释: 在我的GraphQL关联问题,graphql,lodash,express-graphql,Graphql,Lodash,Express Graphql,在深入研究代码之前,以下是对我的问题的高级解释: 在我的GraphQL模式中,我有两种根类型:开发人员和项目。我试图找到属于给定项目的所有开发人员。查询可能如下所示: { project(id:2) { title developers { firstName lastName } } } 目前,我为开发人员获得了一个null值 虚拟数据 const developers = [ { id: '1', firstNam
GraphQL
模式中,我有两种根类型:开发人员和项目。我试图找到属于给定项目的所有开发人员。查询可能如下所示:
{
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,
}
]
因此,布伦特在这两个项目上都有工作。劳拉参与了第二个项目。我的问题出现在ProjectType
中的resolve
功能中。我试过很多问题,但似乎都不管用
项目类型
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 }
})
})
DeveloperType
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 }
})
})
因此,您需要返回所有在其
项目中具有当前项目的id
的开发人员,对吗
首先,\uuq.find
无法帮助您,因为它返回第一个匹配的元素,您需要与开发人员一起获取数组(因为字段具有graphqlist
类型)
那你呢
resolve(parent, args) {
return developers.filter(
({projectIds}) => projectIds.indexOf(parent.id) !== -1
);
}
这对我来说很有意义。我曾经非常接近过滤器,但现在看看哪里出了问题。非常感谢。