0

I am new to graphql and want to understand the concept here. I have this graphql schema (stitched using graphic-tools). Not all cars have registration. So if I query for 5 cars and one car doesn’t have a registration (no id to link between cars and registration), my whole query fails.

How do I handle this and return null for that 1 car and return registration details for the other 4?

{
  Vehicles {
    Cars {
      id
      registration {
        id
      }
    }
  }
}
aiiwa
  • 591
  • 7
  • 27

1 Answers1

2

If you mark a field as non-null (by appending ! to the type) and then resolve that field to null, GraphQL will always throw an error -- that's unavoidable. If it's possible for a field to end up null in the normal operation of your API, you should probably make it nullable.

However, errors "bubble up" to the nearest nullable field.

So given a schema like this:

type Query {
  cars: [Car!]!
}

type Car {
  registration: Registration!
}

and this query

{
  cars {
    registrations
  }
}

resolving the registration field for any one Car to null will result in the following because the cars field is non-null and each individual Car must also not be null:

{
  "data": null,
  "errors": [...]
}

If you make the cars field nullable ([Car!]), the error will stop there:

{
  "data": {
    "cars": null
  },
  "errors": [...]
}

However, you can make each Car nullable (whether the field is or not), which will let the error stop there and result in an array of objects and nulls (the nulls being the cars that errored). So making the cars type [Car]! or [Car] will give us:

{
  "data": {
    "cars": [{...}, {...}, null]
  },
  "errors": [...]
}
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183