Does GraphQL have the possibility for the client to tell the server that it wants a field only if that field is not null
?
Given the query
query HeroAndFriends {
hero {
name
friends {
name
}
}
}
the response should then look like
{
"data": {
"hero": {
"friends": [
{
"name": "Luke Skywalker"
},
{
"name": "Han Solo"
},
{
"name": "Leia Organa"
}
]
}
}
}
instead of
{
"data": {
"hero": {
"name": null,
"friends": [
{
"name": "Luke Skywalker"
},
{
"name": "Han Solo"
},
{
"name": "Leia Organa"
}
]
}
}
}
Is this possible without violating the GraphQL specification?
Nulls in the query A GraphQL query can have fields and inputs, with or without variables. Fields are always optional, whether nullable or not. In inputs, such as field arguments, nullable types are always optional and non‐null types are always required.
In JavaScript functions without an explicit return statement implicitly return undefined . So our function creates a Promise and then immediately returns undefined , causing GraphQL to return null for the field.
The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).
The server's field resolver returned an explicit null. The field resolver throws. In this case GraphQL will return null for that field. This is true even if the server resolver's return type is non-nullable.
As far as I know this is not possible, there are directives like @skip and @include. Directives but they need a variable, I think you can make your case with the graphql team to extend the directives to only include the field if it's not null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With