Search code examples
scalagraphqlsangria

Know specified fields on serverside in GraphQL / Sangria-Graphql


When a client sends a request, I want to know what are the fields client has requested for data. For example,

{
  user {
    name
    address
  }
}

In the above request, client has requested name field and address field of the user. how do I know/get these specified fields i.e. name and address in the sangria-graphql Server while executing the query?


Solution

  • you have to use 4th parameter in resolve()

    resolve: (obj, args, auth, fieldASTs) => {
        /* all your fields are present in selections
           please check the fieldASTs JSON path it may vary if you are using relay
                                                                    connections */
      const requiredFields = fieldASTs.fieldNodes[0].selectionSet.selections.map(
          (set) => set.name.value
       );
      // requiredFields will contain the name and address
    }
    /* fieldASTs contains fieldNames, fieldNodes and every details about your Schema 
     you can get your specified fields inside fieldNodes like */