Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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)

like image 234
Arseniy-II Avatar asked May 11 '26 07:05

Arseniy-II


1 Answers

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.

like image 117
Daniel Rearden Avatar answered May 15 '26 06:05

Daniel Rearden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!