GraphQL has multiple built-in directives like @deprecated, @include, @skip and some others like @stream and @defer that are not part of the official spec (yet).
With the @include directive you can conditionally include fields based on a specified argument:
query Hero($episode: Episode, $withFriends: Boolean!) { | |
hero(episode: $episode) { | |
name | |
friends @include(if: $withFriends) { | |
name | |
} | |
} | |
} |
The @skip directive does exactly the opposite and excludes fields based on a specified argument:
query Hero($episode: Episode, $skipFriends: Boolean!) { | |
hero(episode: $episode) { | |
name | |
friends @skip(if: $skipFriends) { | |
name | |
} | |
} | |
} |
But applying these directives for every field that should be included or excluded feels like a lot of repetition:
query Hero($episode: Episode, $includeFields: Boolean!) { | |
hero(episode: $episode) { | |
name | |
height @include(if: $includeFields) | |
appearsIn @include(if: $includeFields) | |
starships @include(if: $includeFields) | |
totalCredits @include(if: $includeFields) | |
} | |
} |
Here is a trick for you, the @skip
and @include
directives can be used on fields, fragment spreads, and inline fragments. This can help us to make our GraphQL queries more readable.
Here is the example rewritten using an inline fragment:
query Hero($episode: Episode, $includeFields: Boolean!) { | |
hero(episode: $episode) { | |
name | |
... on Character @include(if: $includeFields){ | |
height | |
appearsIn | |
starships | |
totalCredits | |
} | |
} | |
} |
And here is the same example with the fragment spread into the query:
fragment Details on User { | |
name | |
role | |
} | |
query Hero($episode: Episode, $includeFields: Boolean!) { | |
hero(episode: $episode) { | |
name | |
...Details @include(if: $includeFields) | |
} | |
} |
No comments:
Post a Comment