GraphQL query: only include field if not null
Asked Answered
E

2

25

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?

Eclair answered 6/4, 2016 at 12:58 Comment(3)
Just curious to know: what is the use-case of this behaviour?Mcbryde
@AhmadFerdousBinAlam I have a Kotlin data class with default (non-null) values that I don't want to be overwritten when deserializing.Eclair
@Ahmad Ferdous, regarding the use-case, what if the server returns arrays of items that have sparse data? like each object has many fields, only a few of which actually contain something rather than null. Would it not be better to exclude those fields from the payload to decrease the overall size of the api response?Protium
S
7

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.

Spickandspan answered 7/4, 2016 at 8:44 Comment(0)
S
-2

You can use this ES6 syntax in front-end:

Object.keys(data).forEach((key) => (data[key] == null) && delete data[key]);
Salchunas answered 1/8, 2018 at 22:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.