fweigl
fweigl

Reputation: 22038

GraphQL query: only include field if not null

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?

Upvotes: 25

Views: 17659

Answers (2)

Filip K
Filip K

Reputation: 23

You can use this ES6 syntax in front-end:

Object.keys(data).forEach((key) => (data[key] == null) && delete data[key]);

Upvotes: -2

YasserKaddour
YasserKaddour

Reputation: 930

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.

Upvotes: 7

Related Questions