简体   繁体   中英

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
    }
  }
}`;

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM