4

is there a way to retrieve the list of the fields were requested in a GraphQL query by a client?

Lets assume I have the following types:

type Book {

  isbn: String
  title: String
  genre: String
  author: Author
}

type Author {

  name: String
  surname: String
  age: Int
}

Is there a way on Java side inside a method annotated with @GraphQLQuery to know the fields were requested by the client?

For example, having the following queries:

query {

  book ( isbn = "12345" ) {
  
    title
    genre
  }
}

query {

  book ( isbn = "12345" ) {
  
    title
    author {
    
      name
      surname
    }
  }
}

I can know the first query requested the fields title and genre of Book and the second required title from Book and also name and surname of the Author ?

Thanks Massimo

Massimo Da Ros
  • 393
  • 3
  • 11

1 Answers1

5

You can obtain this info via @GraphQLEnvironment. If you just need the immediate subfields, you can inject the names like this:

@GraphQLQuery
public Book book(String isbn, @GraphQLEnvironment Set<String> subfields) {
    ...
}

If you want all the subfields, or other selection info, you can inject ResolutionEnvironment and get DataFetcherEnvironment from there. That in turn gives you access to the whole SelectionSet.

@GraphQLQuery
public Book book(String isbn, @GraphQLEnvironment ResolutionEnvironment env) {
    DataFetchingFieldSelectionSet selection = env.dataFetchingEnvironment.getSelectionSet();
     ...
}
kaqqao
  • 12,984
  • 10
  • 64
  • 118
  • Thanks @kaqqao, it works ! My intent was to extract the required fields in order to build dynamic entity graphs and use them with the underlying DB doing only the required joins based on what the client wants. I've got an implementation already :) – Massimo Da Ros May 09 '20 at 16:54
  • I'd be interested in seeing that in action, if there's anything you can share :) – kaqqao May 09 '20 at 18:29
  • 1
    Here is the Github repo (only a training POC in order to explore GraphQL features): https://github.com/m-daros/graphql-spring-boot. You can find the code that is based on your hints in this class: https://github.com/m-daros/graphql-spring-boot/blob/master/src/main/java/mdaros/training/graphql/spring/boot/service/AbstractService.java. :). You can run the application and try some query using the GUI http://localhost:8080/gui – Massimo Da Ros May 09 '20 at 19:17