Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to skip part of a query with apollo-client

I'm trying to perform 3 unique searches inside one query. The problem is that my search "filter" type is mandatory in the schema but in the front-end it's optional. If a null value is provided inside my filter then I'll get a graphql error.

I want to skip searching for mainSearchData, firstComparisonSearchData or secondComparisonSearchData depending on whether the search filters contain data.

I know that I can use the skip function to ignore the whole query but how can I achieve the same for part of the query? Or alternatively, how can I compose these as separate queries but perform just one request?

const GROWTH_QUERY = gql`query aggregateQuery($mainFilter: filter!, $firstComparisonFilter: filter!, $secondComparisonFilter: filter! $interval: interval!) {
  mainSearchData: groupBy(filter: $mainFilter, first: 20, after: 0) {
    items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {
      date
      count
    }
  }
  firstComparisonSearchData: groupBy(filter: $firstComparisonFilter, first: 20, after: 0) {
    items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {
      date
      count
    }
  }
  secondComparisonSearchData: groupBy(filter: $secondComparisonFilter, first: 20, after: 0) {
    items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {
      date
      count
    }
  }
}`;
like image 947
JamesR Avatar asked May 08 '17 11:05

JamesR


People also ask

What is skip in GraphQL?

@skip and @include directives can be applied to query fields. They allow you to skip or include a field based on the value of the if argument that is passed to the directive.


1 Answers

You can use the skip function on the fields themselves.

For example:

const GROWTH_QUERY = gql`query aggregateQuery($mainFilter: filter!, $firstComparisonFilter: filter!, $secondComparisonFilter: filter! $interval: interval!) @skip(if: ...) {
  mainSearchData: groupBy(filter: $mainFilter, first: 20, after: 0) {
    items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {
      date
      count
    }
  }
  firstComparisonSearchData: groupBy(filter: $firstComparisonFilter, first: 20, after: 0) @skip(if: ...) {
    items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {
      date
      count
    }
  }
  secondComparisonSearchData: groupBy(filter: $secondComparisonFilter, first: 20, after: 0) @skip(if: ...) {
    items: publicationDate(interval: $interval, minDocCount: 1, sort: DESC) {
      date
      count
    }
  }
}`;

Notice the @skip(if: ...) statements after the alias calls on mainSearchData, firstComparisonSearchData, and secondComparisonSearchData.

like image 132
vince Avatar answered Oct 26 '22 08:10

vince