Thursday, 1 June 2017

How to omit empty or null values when querying with GraphQL?

I am learning to use GraphQL and Mongoose with Express. I'm wondering how to write queries that omit empty values. For some reason I thought GraphQL didn't return null values but it seems I misunderstood something I read or heard.

This is the response I am getting.

{
  "data": {
    "jobs": [
      {
        "title": "Job 666 WindowCorp",
        "customers": [
          {
            "id": "124123515",
            "createdAt": 1492923538348,
            "lastModifiedAt": 1493269718079,
            "firstName": "Mirage Windows Aus PTY LTD ABN 1234",
            "phoneNumber": {
              "humanFormat": null,
              "machineFormat": null
            }
          }
        ]
      },
      {
        "title": "Maxiboon ",
        "customers": [
          {
            "id": "1414124",
            "createdAt": 1495419565855,
            "lastModifiedAt": null,
            "firstName": "Liam Test",
            "phoneNumber": {
              "humanFormat": "0400000000",
              "machineFormat": "+6140000000"
            }
          }
        ]
      }
    ]
  }
}

I would like for the items with null values to be omitted from the response.

Is this possible?

Query

{   
  jobs {
    title,
    customers {
      id,
      createdAt,
      lastModifiedAt,
      firstName,
      phoneNumber {
        humanFormat,
        machineFormat
      }
    }
  }
}

Type

const JobType = new GraphQLObjectType({
  name: 'JobType',
  fields: () => ({
    id: { type: GraphQLID },
    title: { type: GraphQLString },
    jobNumber: { type: GraphQLInt  },
    customers: {
      type: new GraphQLList(CustomerType),
      resolve(parentValue) {
        return Job.findCustomers(parentValue.id);
      }
    }
  })
});

RootQuery

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: () => ({
    jobs: {
      type: new GraphQLList(JobType),
      resolve() {
        return Job.find({});
      }
    },
    job: {
      type: JobType,
      args: { id:  { type: new GraphQLNonNull(GraphQLID) } },
      resolve(parentValue, { id }) {
        return Job.findById(id);
      }
    },
    customers: {
      type: new GraphQLList(CustomerType),
      resolve() {
        return Customer.find({});
      }
    },
    customer: {
      type: JobType,
      args: { id:  { type: new GraphQLNonNull(GraphQLID) } },
      resolve(parentValue, { id }) {
        return Customer.findById(id);
      }
    },
  })
});



via Dom Hede

No comments:

Post a Comment