【问题标题】:GraphQL association issueGraphQL 关联问题
【发布时间】:2019-06-27 23:38:08
【问题描述】:

在深入研究代码之前,这里是对我的问题的高级解释:

在我的 GraphQL 架构中,我有两种根类型:DevelopersProjects。我试图找到属于给定项目的所有开发人员。查询可能如下所示:

{
  project(id:2) {
    title
    developers {
      firstName
      lastName
    }
  }
}

目前,我正在为 developers 获得 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 }
  })
})

【问题讨论】:

    标签: graphql lodash express-graphql


    【解决方案1】:

    所以您需要返回所有在其.projectIds 中具有当前项目id 的开发人员,对吗?

    首先,_.find 无能为力,因为它返回第一个匹配的元素,您需要与开发人员获取数组(因为字段具有 GraphQLList 类型)。

    那么

    resolve(parent, args) {
        return developers.filter(
            ({projectIds}) => projectIds.indexOf(parent.id) !== -1
        );
    }
    

    【讨论】:

    • 这对我来说很有意义。我已经非常接近过滤器了,但现在看看我哪里出错了。谢谢!
    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    相关资源
    最近更新 更多