微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何避免在 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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。