How to get requested fields inside GraphQL resolver?

arslan picture arslan · Dec 28, 2017 · Viewed 11.4k times · Source

I am using graphql-tools. After receiving a GraphQL query, I execute a search using ElasticSearch and return the data.

However, usually the requested query includes only a few of the possible fields, not all. I want to pass only the requested fields to ElasticSearch. First, I need to get the requested fields.

I can already get the whole query as a string. For example, in the resolver,

const resolvers = {
  Query: {
    async user(p, args, context) {
      //can print  query as following
      console.log(context.query)                
    }
    .....
  }
}

It prints as

query User { user(id:"111") { id  name address } }

Is there any way to get the requested fields in a format like

{ id:"",  name:"", address:"" }

Answer

s.meijer picture s.meijer · May 23, 2018

There is an info object passed as the 4th argument in the resolver. This argument contains the information you're looking for.

It can be helpful to use a library as graphql-fields to help you parse the graphql query data:

const graphqlFields = require('graphql-fields');

const resolvers = {
  Query: {
    async user(_, args, context, info) {
      const topLevelFields = graphqlFields(info);
      console.log(Object.keys(topLevelFields)); // ['id', 'name', 'address']
    },
};