【问题标题】:GraphQL, Apollo Server Federated schemaGraphQL,Apollo 服务器联合模式
【发布时间】:2020-12-21 01:10:59
【问题描述】:

查询时出现此错误:

"Cannot return null for non-nullable field Transaction.createdAt."

这是查询:

query getMyTransactions {
  getMyTransactions {
    id
    createdAt
  }
}

此查询的架构是:

extend type Transaction @key(fields: "id") {
  id: ID! @external
}

type Query {
  getMyTransactions: [Transaction!]!
}

而另一个架构有Transaction 类型:

type Transaction @key(fields: "id") {
  id: ID!
  createdAt: String!
}

有什么问题?

编辑:如果我查询:

getMyTransactions {
  id
}

工作正常,我得到了查询的所有id,但如果我包含另一个属性,查询将失败。

【问题讨论】:

    标签: graphql apollo-server apollo-federation


    【解决方案1】:

    简单来说 - 您将 createdAt 类型声明为 non-null 值,但在您的数据中某处 createdAtnull

    createdAt: String!

    !在类型名称之后。这意味着我们的服务器总是希望 为该字段返回一个非空值,如果它最终得到一个 实际会触发 GraphQL 执行错误的 null 值, 让客户知道出了问题。 GraphQl docs

    示例

    对于这个远程/本地数据(createdAtmissing 来自第一个对象):

    const Transaction = [
      {
        id: "1",
        /* createdAt: "01/09/2020" */ /* missing from the data */
      },
      {
        id: "2",
        createdAt: "02/09/2020"
      }
    ];
    

    执行查询

    query{
      getMyTransactions {
        id
        createdAt
        }
    }
    

    抛出错误:

    "message": "不能为非空字段返回空值 Transaction.createdAt.",

    解决这个问题:

    • 选项 1: 添加一些 解析器 逻辑和/或添加与所需数据相关的验证。
    • 选项 2:createdAt 中删除 require(允许返回 null):

    【讨论】:

    • 这就是我的想法,但检查数据,createdAt 存在于表的每个项目上。现在,如果我将 createdAt: String 放在 Transaction 类型上,我会将每个 createdAt 都设为 null。我认为我对如何使用联合选项(@key、@external 等)有误
    猜你喜欢
    • 2018-06-23
    • 2021-12-01
    • 2019-03-01
    • 2021-08-21
    • 2021-10-04
    • 2017-11-07
    • 2018-01-05
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多