Search code examples
javagraphqlgraphql-java

Access Selection Set of a graphQL query


Is it possible to access a GraphQL Selection Set from a query (String) in Java ?

For instance from the string below:

"{
    data {
        title
        description
    }
}"

get a list of fields : ["data", "title", "description"]


Solution

  • If you mean to just extract the fields directly from a string, you can parse the query and recursively traverse the resulting document to collect the names.

    You can parse the query this way:

    Parser parser = new Parser();
    Document document = parser.parseDocument(queryString);
    

    The Document object is the query parsed into a tree structure. You can traverse it to extract what you need.

    If you just need the selection set during field resolution (e.g. to see what sub-selections are requested so you optimize the fetching logic e.g. to fire a SELECT title, description FROM ... instead of a SELECT * FROM ...) there's an easier way as DataFetchingEnvironment already provides access to the selection set:

    DataFetchingFieldSelectionSet selectionSet = dataFetchingEnv.getSelectionSet();
    Map<String, List<Field>> fieldsByName = selectionSet.get();
    

    If you need to drill deeper than one level, you can use DataFetchingFieldSelectionSet.contains which accepts a glob pattern e.g. parent/*/grandChild and tells you whether such a field was requested.

    You can also get the current Field from the DataFetchingEnvironment:

    List<Field> getFields().get(0)
    

    And from there you can extract the sub-selection for the current field. This last approach only makes sense if there are potentially conditional selections (i.e. the current field is an interface, so the selection might depend on the implementation e.g. ... on Impl { title }).