Search code examples
graphqlapollorelay

"else" with GraphQL


How to achieve "else" effect with GQL directives

There is a way to fetch something conditionally with gql using @include(if: $withFriends)

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

But I want to fetch something else if $withFriends is false. I can achieve it by passing additional variable $notWithFriends

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

Question: is it possible to avoid using additional variable?

Something like this: @include(else: $withFriends) or @include(ifNot: $withFriends) or @include(if: !$withFriends)


Solution

  • You can use @skip directive, which works like the opposite of @include -- it omits the field from the selection set if the if argument is true:

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

    In this way, if $withFriends is true, only name and friends will be selected. If it is false, only name and appearsIn will be selected.