GraphQL关联问题

问题描述 投票:0回答:1

在深入代码之前,这里是我的问题的一个高层次的解释:

在我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,
  }
]

所以,布伦特已经在这两个项目的工作。劳拉在第二个项目的工作。我的问题是在resolveProjectType功能。我试过许多查询,但没有一个似乎工作。

项目类型

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: ? });
      }

    }
  })
})

DeveloperType

const DeveloperType = new GraphQLObjectType({
  name: 'Developer',
  fields: () => ({
    id: { type: GraphQLID },
    firstName: { type: GraphQLString },
    lastName: { type: GraphQLString }
  })
})
graphql lodash express-graphql
1个回答
1
投票

所以,你需要返回其当前项目的在他们的id .projectIds,右边的所有开发人员?

首先,_.find不能帮助,因为它会返回第一个匹配元素,你需要得到与开发商阵列(因为现场有GraphQLList型)。

因此,如何

resolve(parent, args) {
    return developers.filter(
        ({projectIds}) => projectIds.indexOf(parent.id) !== -1
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.