Search code examples
javagraphqlapolloapollo-client

How to dynamically adjust Query shape (fields) using Apollo graphql?


i want to Query only selected fields using Apollo graphql in java.

Dont find any article which shows how we can achieve that

I define my query in .graphql file like this,

query getResources{
   resources(filterBy: {} ) {
      edges{
         cursor
         node   {
                id
                name
                canonicalName
                description
                createdAt
                updatedAt
                createdBy
                updatedBy
         }
      }
      pageInfo{
          hasPreviousPage
          hasNextPage
      }
   }
}

while making the query request execute = apolloClient.query(getResourcesQuery).execute();

i want to change the getResourcesQuery object to only query certain fields. how can we do that ?


Solution

  • Apollo Android is not really a query builder -- you can't specify individual fields to add to a selection set. Instead, your provided query is sent as-is. If you're looking for that sort of functionality, you may want to look into a different client (like nodes).

    That said, you can utilize the @skip and @include directives, combined with some variables, to dynamically control what's included in your request's selection set. For example:

    query getResources(
      $includeEdges: Boolean = true
      $includePageInfo: Boolean = true
    ) {
      resources(filterBy: {}) {
        edges @include(if: $includeEdges) {
          cursor
          node {
            id
            name
            canonicalName
            description
            createdAt
            updatedAt
            createdBy
            updatedBy
          }
        }
        pageInfo @include(if: $includePageInfo) {
          hasPreviousPage
          hasNextPage
        }
      }
    }
    

    Then just add the variables:

    GetResources getResourcesQuery = GetResources.builder()
        .includePageInfo(false)
        .build();
    
    apolloClient().query(getResourcesQuery).execute();