Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL query: only include field if not null

Tags:

graphql

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?

like image 893
fweigl Avatar asked Apr 06 '16 12:04

fweigl


People also ask

How do you handle null values in GraphQL?

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.

Does GraphQL return null or undefined?

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.

What is __ Typename in GraphQL?

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

Can GraphQL return null?

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.


1 Answers

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.

like image 66
YasserKaddour Avatar answered Oct 21 '22 03:10

YasserKaddour