如何处理 GraphQL 模式中的空值
How to deal with nulls in GraphQL schema
当 FlightSchedule.operatingAirline 为空(根据架构完全有效)并且客户端查询 FlightSchedule.operatingAirline.id 时,我不断收到 "Cannot return null for non-nullable field Airline.id." 错误。如何解决这个问题?将 Airline.id、Airline.code 和 Airline.name 设置为可为 null 可以修复此问题,但不是解决此问题的正确方法,因为如果航空公司存在,这 3 个字段也将始终存在。以下是我的架构:
type Airline {
id: String!,
code: String!,
name: String!
}
type FlightSchedule {
airline: Airline!
operatingAirline: Airline
}
下面是我的查询:
getFlightSchedules {
airline
{
id
code
name
}
operatingAirline
{
id
code
name
}
}
如果在解析过程中遇到错误,字段将解析为空。这包括您遇到的验证错误。来自规范:
If during ExecuteSelectionSet() a field with a non‐null fieldType throws a field error then that error must propagate to this entire selection set, either resolving to null if allowed or further propagated to a parent field.
If this occurs, any sibling fields which have not yet executed or have not yet yielded a value may be cancelled to avoid unnecessary work.
换句话说,如果父字段属于特定对象类型,and 该类型具有不可为 null 的字段,and 该字段解析为 null,该父字段也将解析为 null。父字段不能 return 一个无效的对象(在本例中是因为它有一个非空字段 return null),所以它唯一能做的就是 return null。当然,如果父字段本身是非空的,则此行为会向上传播到树中,直到最终遇到可为空的字段。
那么,为什么会出现该错误?因为 operatingAirline
的解析器 not returning null。它是 returning 某种对象(不完整的航空公司对象、数组、字符串或其他东西),然后 GraphQL 会有效地尝试将其强制转换为 Airline
类型。已请求 id 字段,但它根据 operatingAirline
的解析器 return 编辑的对象解析为 null。由于 id
被请求并且 return 为空,整个 operatingAirline
字段验证失败并且 return 为空。
当 FlightSchedule.operatingAirline 为空(根据架构完全有效)并且客户端查询 FlightSchedule.operatingAirline.id 时,我不断收到 "Cannot return null for non-nullable field Airline.id." 错误。如何解决这个问题?将 Airline.id、Airline.code 和 Airline.name 设置为可为 null 可以修复此问题,但不是解决此问题的正确方法,因为如果航空公司存在,这 3 个字段也将始终存在。以下是我的架构:
type Airline {
id: String!,
code: String!,
name: String!
}
type FlightSchedule {
airline: Airline!
operatingAirline: Airline
}
下面是我的查询:
getFlightSchedules {
airline
{
id
code
name
}
operatingAirline
{
id
code
name
}
}
如果在解析过程中遇到错误,字段将解析为空。这包括您遇到的验证错误。来自规范:
If during ExecuteSelectionSet() a field with a non‐null fieldType throws a field error then that error must propagate to this entire selection set, either resolving to null if allowed or further propagated to a parent field.
If this occurs, any sibling fields which have not yet executed or have not yet yielded a value may be cancelled to avoid unnecessary work.
换句话说,如果父字段属于特定对象类型,and 该类型具有不可为 null 的字段,and 该字段解析为 null,该父字段也将解析为 null。父字段不能 return 一个无效的对象(在本例中是因为它有一个非空字段 return null),所以它唯一能做的就是 return null。当然,如果父字段本身是非空的,则此行为会向上传播到树中,直到最终遇到可为空的字段。
那么,为什么会出现该错误?因为 operatingAirline
的解析器 not returning null。它是 returning 某种对象(不完整的航空公司对象、数组、字符串或其他东西),然后 GraphQL 会有效地尝试将其强制转换为 Airline
类型。已请求 id 字段,但它根据 operatingAirline
的解析器 return 编辑的对象解析为 null。由于 id
被请求并且 return 为空,整个 operatingAirline
字段验证失败并且 return 为空。