Breaking

Tuesday, October 5, 2021

GraphQL - Use @skip and @include on fragments

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
}
}
}
view raw hero.graphql hosted with ❤ by GitHub

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
}
}
}
view raw hero.graphql hosted with ❤ by GitHub

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)
}
}
view raw hero.graphql hosted with ❤ by GitHub

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
}
}
}
view raw hero.graphql hosted with ❤ by GitHub

And here is the same example with the fragment spread into the query:

fragment Details on User {
name
email
role
}
query Hero($episode: Episode, $includeFields: Boolean!) {
hero(episode: $episode) {
name
...Details @include(if: $includeFields)
}
}
view raw hero.graphql hosted with ❤ by GitHub

No comments:

Post a Comment