Skip to content

DataFetchingEnvironment should always have a way to get field sub-selection #377

Closed

Description

@kaqqao

Currently, DataFetchingEnvironment has no way to fetch only the required fields if the query uses fragments.
DataFetchingEnvironment#getFields currently has populated SelectionSet only for Field and InlineFragment, while it is always blank for Fragment. Additionally, fragment definitions are inaccessible as they're only kept in ExecutionContext.

Activity

  1. bbakerman commented on Apr 27, 2017

    @bbakerman
    Member

    One other concern I had was around query proxiying.

    Imagine you have this query

      query {
             handledByGraphqlProxyServer1 {
                       name
                       address {
                           street
                           postcode
                      }
                      age
            }
           handledByGraphqlProxyServer2 {
                     height
                     weight
          }
    }
    

    Now imagine the backing data fetcher of handledByGraphqlProxyServer1 is in fact going to call out to a remote graphql server and pass on the inner query part

    eg: effectively

     query {
          name
          address {
                 street
                 postcode
          }
          age
    }
    

    So how could we implement this? I dont think today we can.

    Because the selection set (including deeply beyond this objecy) is available to the data fetcher.

  2. bbakerman commented on May 2, 2017

    @bbakerman
    Member

    I looked further into this issue and I think this is available now

    @apottere added #392

    I confirmed this locally using this little wrapper class

     class DataFetcherProxy implements DataFetcher {
        final DataFetcher delegate
    
        DataFetcherProxy(DataFetcher delegate) {
            this.delegate = delegate
        }
    
        @Override
        Object get(DataFetchingEnvironment environment) {
            String fields = printFields(environment.getFields())
            String fragments = printFragments(environment.getFragmentsByName())
            System.out.printf("\n\nfields :\n %s",fields)
            System.out.printf("\nfragments :\n %s",fragments)
            return delegate.get(environment)
        }
    
        String printFragments(Map<String, FragmentDefinition> fragmentDefinitionMap) {
            return fragmentDefinitionMap.values().stream().map({ node -> AstPrinter.printAst(node) }).collect(Collectors.joining("\n"))
        }
    
        String printFields(List<Field> fields) {
            return fields.stream().map({ f -> AstPrinter.printAst(f) }).collect(Collectors.joining("\n"))
        }
    }
    

    I put it over the starwars schema like this :

    query UseFragment {
            luke: human(id: "1000") {
                ...HumanFragment
                homePlanet
            }
            leia: human(id: "1003") {
                ...HumanFragment
                appearsIn
            }
        }
        fragment HumanFragment on Human {
            name
            ...FriendsAndFriendsFragment
            
        }
        
        fragment FriendsAndFriendsFragment on Character {
            friends {
                name 
                friends {
                    name
                }
           }
        }
    

    The DataFetchingEnvironment now has the selection set via fields and fragments. You would need to combine them to synthesize a pure list of fields.

    The system output is given below

    ields :
        luke: human(id: "1000") {
        ...HumanFragment
        homePlanet
        }
        fragments :
        fragment HumanFragment on Human {
        name
        ...FriendsAndFriendsFragment
        }
        fragment FriendsAndFriendsFragment on Character {
        friends {
            name
            friends {
            name
            }
        }
        }
    
        fields :
        friends {
        name
        friends {
            name
        }
        }
        fragments :
        fragment HumanFragment on Human {
        name
        ...FriendsAndFriendsFragment
        }
        fragment FriendsAndFriendsFragment on Character {
        friends {
            name
            friends {
            name
            }
        }
        }
    
        fields :
        leia: human(id: "1003") {
        ...HumanFragment
        appearsIn
        }
        fragments :
        fragment HumanFragment on Human {
        name
        ...FriendsAndFriendsFragment
        }
        fragment FriendsAndFriendsFragment on Character {
        friends {
            name
            friends {
            name
            }
        }
        }
    
        fields :
        friends {
        name
        friends {
            name
        }
        }
        fragments :
        fragment HumanFragment on Human {
        name
        ...FriendsAndFriendsFragment
        }
        fragment FriendsAndFriendsFragment on Character {
        friends {
            name
            friends {
            name
            }
        }
        }
    

    Notice how the fields are calculated as we go down but the fragments are global in the query. This is defined in the grammar

    document : definition+;
    
    definition:
    operationDefinition |
    fragmentDefinition |
    typeSystemDefinition
    ;
    
    fragmentDefinition : 'fragment' fragmentName typeCondition directives? selectionSet;
    

    So they will always be "global" and need replacing as your data fetcher executes.

    You could nominally use FieldCollector but it requires ExecutionContext which you dont have

            Map<String, List<Field>> subFields = new LinkedHashMap<>();
            List<String> visitedFragments = new ArrayList<>();
            for (Field field : fields) {
                  if (field.getSelectionSet() == null) continue;
                fieldCollector.collectFields(executionContext, resolvedType, field.getSelectionSet(), visitedFragments, subFields);
            }
    

    Perhaps we should fix DataFetchingEnvironement so it has the executionContext and hence can call fieldCollector

  3. apottere commented on May 2, 2017

    @apottere
    Contributor

    Yeah, fragment definitions are available on the DataFetchingEnvironment now.

  4. apottere commented on May 2, 2017

    @apottere
    Contributor

    Oh, missed your last observation. I'm all for adding the ExecutionContext to the DataFetchingEnvironment, but there was a comment on the last PR that tried to fix a similar issue about not expanding the API surface by exposing the ExecutionContext, so that's why I didn't in my PR.

  5. kaqqao commented on May 2, 2017

    @kaqqao
    ContributorAuthor

    Ah, perfect, this has actually been solved already! Thanks for the explanations @bbakerman and @apottere !
    And this issue is basically just a duplicate of #303 so I'll close it.

  6. kaqqao commented on May 2, 2017

    @kaqqao
    ContributorAuthor

    Actually, when I think about it better, maybe you wanted to keep it open until the decision on FieldCollector and the query proxying use-case from above.

    Thinking of FieldCollector, perhaps it can be refactored a little to have methods that allow collecting based on fragment definitions only (when directives had already been processed) so that it can be used from within DataFetcher?

  7. reopened this on May 2, 2017
  8. added a commit that references this issue on May 2, 2017
  9. bbakerman commented on May 2, 2017

    @bbakerman
    Member

    Thinking of FieldCollector, perhaps it can be refactored a little to have methods that allow collecting based on fragment definitions only (when directives had already been processed) so that it can be used from within DataFetcher?

    Can you give examples of this. Having the specific use cases allows for unit tests to be more easily written

  10. kaqqao commented on May 4, 2017

    @kaqqao
    ContributorAuthor

    @bbakerman I was having similar ideas to what you ended up doing in your PR. I was thinking of refactoring FieldCollector in way that would allow it to be created ("initialized") with the variables, and passed to DataFetchingEnvironement, which would then be able to use it without having to pass variables again. It could even hide FieldCollector internally, just exposing the field collection methods itself. Not sure if this is smart, was just thinking aloud.

  11. added a commit that references this issue on May 10, 2017
  12. bbakerman commented on May 10, 2017

    @bbakerman
    Member

    Thanks for the idea. I have implemented it in the way you suggested

  13. added this to the 3.0.0 milestone on May 10, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions