【问题标题】:How to avoid returning null in Apollo Federation GraphQL如何避免在 Apollo Federation GraphQL 中返回 null
【发布时间】:2021-08-15 15:59:15
【问题描述】:

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

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"
            }
          },
          null,
          null,
          null,
          {
            "sku": 99176480310,
            "score": 0.99,
            "product": {
              "title": "Cerveza Boca Negra pilsner 355 ml",
              "name": "Cerveza Boca Negra pilsner"
            }
          },
          null,
          {
            "sku": 8712000030605,
            "score": 0.21,
            "product": {
              "title": "Cerveza Victoria lata 355 ml x12",
              "name": "Cerveza Victoria lata"
            }
          }
        ]
      }

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

【问题讨论】:

    标签: graphql apollo apollo-federation netflix-dgs


    【解决方案1】:

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

    return users.filter(Boolean)
    

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 2021-05-02
      • 2021-01-31
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 2015-02-14
      相关资源
      最近更新 更多