可以使用apollo-client跳过部分查询

Jam*_*esR 3 graphql react-apollo apollo-client

我正在尝试在一个查询中执行3个唯一搜索.问题是我的搜索"过滤器"类型在模式中是必需的,但在前端它是可选的.如果在我的过滤器中提供了空值,那么我将得到graphql错误.

我想跳过搜索mainSearchData,firstComparisonSearchData或secondComparisonSearchData,具体取决于搜索过滤器是否包含数据.

我知道我可以使用该skip函数来忽略整个查询但是如何在查询的一部分中实现相同的功能呢?或者,我如何将这些作为单独的查询组成,但只执行一个请求?

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
    }
  }
}`;
Run Code Online (Sandbox Code Playgroud)

vin*_*nce 6

您可以skip在字段本身上使用该功能.

例如:

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
    }
  }
}`;
Run Code Online (Sandbox Code Playgroud)

注意@skip(if: ...)语句的别名电话后mainSearchData,firstComparisonSearchDatasecondComparisonSearchData.