Search code examples
javascriptgraphqlapolloapollo-server

Apollo resolver chain returning null


Gone over the docs many times now but I don't think I'm getting it. I have the following (simplified) definitions:

type executive {
  executiveName: String,
  office: [office]
}
type office {
  officeName: String,
}

It's possible that there are many (thousands) of offices that could be returned, so I'd like to break apart the call between executives and offices so I can show executives first and load offices in the background. I call my API like so:

query {
    executives {
      executiveName
      office {
        officeName
      } 
    }
}

Question 1: Would having this hierarchical structure work for this scenario? Is there a better way you can suggest I can structure my query?

I also have the following resolvers:

const queryType = new GraphQLObjectType({
  name: "Query",
  description: "Query entry point for the application",
  fields: () => ({
    executives: {
      type: GraphQLList(executives),
      resolve: (_, __, { dataSources }) => {
        return dataSources.elasticAPI.getExecutives();
      }
    },
    {
      office: {
        type: office,
        name: "office",
        resolve: async (_, { startDate, endDate }, { dataSources }) => {
          const offices = await dataSources.elasticAPI.getOffices(
            startDate,
            endDate
          );
          return offices
        }
      }
    })
  })
})
    

But get the following response:

{
  "data": {
    "executives": [
      {
        "executiveName": "Joe Smith",
        "office": null
      }
      ...
    ]
  }
}

Question 2: Why are my resolvers return null? I would have thought that the offices resolver would have returned the information but it is not being recognized by GraphQL.


Solution

  • Why are my resolvers returning null? I would have thought that the offices resolver would have returned the information but it is not being recognized by GraphQL.

    The office field you showed in your desired schema is part of the executive type, not part of the Query type. Your resolver object needs to reflect that.