Search code examples
graphqlapolloapollo-server

How to Remove null values of Key in GraphQL Response JSON Data


I have TypeDef like this

type Query {
  userList: userListPayload
}

type userListPayload {
  name: String
  test: String
}

Client request is

query {
    userList {
        name
        test
    }
}

Back-End response has not test data. If there is not a value, GraphQL set test value as null. if test is null, I do not want test key. My expectation response is below

{
   "name": "my name"
}

GraphQL response is below

{
   "name": "my name",
   "test": null
}

Is there any way to remove null values ?


Solution

  • Short answer: no.

    Your query is requesting that the return payload include test so you're going to get that variable in your payload.

    If you made test non-nullable in your type, i.e.:

    type userListPayload {
      name: String
      test: String!
    }
    

    Then if test is null you won't get anything back at all (not even name) because one of the required fields is null.