如何避免在 Apollo Federation GraphQL 中返回 null

问题描述

我有两个服务(使用 DGS Netflix 实现),我想使用 apollo 联合进行联合。第一个用户服务,它的模型看起来像这样:

type User @key(fields: "sku") {
    id: ID!
    sku: Long
    score: Float
}

并且每个人都可以拥有来自另一项服务的产品:

type User @key(fields: "sku") @extends {
    sku: Long! @external
    product: Product!
}

而且我想让所有用户都使用他们的产品,但可能会发生用户没有产品的情况。

用户的产品为空时,有没有办法避免返回用户

users: [User]

目前我的回复是这样的:

"errors": [
    {
      "message": "The field at path '/_entities[0]/product' was declared as a non null type,but the code involved in retrieving data has wrongly returned a null value.  The graphql specification requires that the parent field be set to null,or if that is non nullable that it bubble up null to its parent and so on. The non-nullable type is 'Product' within parent type 'User'",} ...
    "data": {
        "users": [
          null,null,{
            "sku": 9002490100490,"score": 0.72,"product": {
              "title": "Sabritas limón 160 g","name": "Sabritas limón"
            }
          },{
            "sku": 99176480310,"score": 0.99,"product": {
              "title": "Cerveza Boca Negra pilsner 355 ml","name": "Cerveza Boca Negra pilsner"
            }
          },{
            "sku": 8712000030605,"score": 0.21,"product": {
              "title": "Cerveza Victoria lata 355 ml x12","name": "Cerveza Victoria lata"
            }
          }
        ]
      }

我想要相同的列表,但列表中没有空值并且没有错误。是否有可能?我正在考虑添加某种删除空元素但无法成功的自定义指令。

解决方法

我还研究了一些指令作为潜在的解决方案,并得出结论认为 GraphQL 不具备这样的能力,因此您必须在代码中的某处执行此操作,例如您可以通过以下方式过滤掉解析器中的响应使用过滤器:

return users.filter(Boolean)