【问题标题】:GraphQL: Return a type with non-nullable id field as a query resultGraphQL:返回具有不可为空 id 字段的类型作为查询结果
【发布时间】:2018-12-19 14:13:37
【问题描述】:

我有这种类型:

  type Profile {
    id: ID! @isUnique
    email: String! @isUnique
    ...
  }

还有一个查询:

profile(email: String!):Profile

当我使用不存在的用户运行查询时,我的底层解析器返回 null,我希望 GraphQL 会喜欢这个。

但是,我得到了这个错误:

Cannot return null for non-nullable field Profile.id.

发生这种情况是因为查询应该返回 Profile 并且 Profile 必须有 id 字段。

但是,查询的返回类型不是不可为空的Profile!,而是Profile,这意味着查询可能什么也不返回。

如何正确解决这个问题?

【问题讨论】:

  • 您能否更新您的问题以包含来自 GraphQL 的完整响应,而不仅仅是错误?
  • 我也有同样的问题,这里有我的完整回复justpaste.it/4pqlr

标签: graphql graphcool


【解决方案1】:

尝试在您的个人资料查询解析器中返回 null。如果您返回类似空对象的内容,Profile 解析器将拾取该对象并尝试将 undefined 返回为 Profile.id,正如您所指出的那样,这是一个架构错误。

试试这样的:

const queryProfileResolver = (_, { email }) => {
  // getProfileByEmail should return null if no match is found
  return getProfileByEmail(email)
}

您的 graphQL 响应将如下所示

{
  data: {
    profile: null
  }
}

【讨论】:

  • 同样的问题,没有解决办法:(
【解决方案2】:

首先你需要删除你的数据库并使用 types.graphql 原样

type Profile {
    id: ID! @isUnique
    email: String! @isUnique 
    ...
  }

部署它,错误就会消失。

发生这种情况的主要原因是您已经部署了不为空的数据,因此无法更改您需要删除我们的数据库,就是这样

【讨论】:

    猜你喜欢
    • 2019-05-28
    • 2019-06-13
    • 2019-10-04
    • 2021-11-27
    • 2021-10-24
    • 2019-07-08
    • 2019-10-25
    • 2019-07-07
    • 1970-01-01
    相关资源
    最近更新 更多