Search code examples
graphqllodashexpress-graphql

GraphQL association issue


Before diving into the code, here is a high-level explanation of my question:

In my GraphQL schema, I have two root types: Developers and Projects. I'm attempting to find all developers who are part of a given project. The query might look like this:

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

Currently, I'm getting a null value for developers.

Dummy data

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

So, Brent has worked on both projects. Laura has worked on the second project. My issue is in the resolve function in ProjectType. I've tried many queries, but none seem to work.

ProjectType

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 }
  })
})

Solution

  • So you need to return all the developers having current project's id in their .projectIds, right?

    First, _.find cannot help since it returns first matched element and you need to get array with developers(since field has GraphQLList type).

    So how about

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