@include(否则为@include(如果不是,则为:graphql

时间:2019-06-14 05:27:19

标签: graphql apollo relay

如何使用GQL指令实现“其他”效果

有一种方法可以使用@include(if: $withFriends)使用gql有条件地获取内容

query Hero($episode: Episode, $withFriends: Boolean!) {
  hero(episode: $episode) {
    name
    friends @include(if: $withFriends) {
      name
    }
  }
}

但是,如果$withFriends为假,我想获取其他信息。我可以通过传递附加变量$notWithFriends

来实现
query Hero($episode: Episode, $withFriends: Boolean!) {
  hero(episode: $episode) {
    name
    friends @include(if: $withFriends) {
      name
    }
    appearsIn @include(if: $notWithFriends)
  }
}

问题:是否可以避免使用其他变量?

类似这样的内容:@include(else: $withFriends)@include(ifNot: $withFriends)@include(if: !$withFriends)

1 个答案:

答案 0 :(得分:1)

您可以使用@skip伪指令,该伪指令的工作方式与@include相反—如果if参数为true,则它会忽略选择集中的字段:< / p>

query Hero($episode: Episode, $withFriends: Boolean!) {
  hero(episode: $episode) {
    name
    friends @include(if: $withFriends) {
      name
    }
    appearsIn @skip(if: $withFriends)
  }
}

通过这种方式,如果$withFriendstrue,则只会选择namefriends。如果为false,则只会选择nameappearsIn