首页 文章

GraphQL:返回一个带有非可空id字段的类型作为查询结果

提问于
浏览
0

我有这种类型:

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

一个查询:

profile(email: String!):Profile

当我用不存在的用户运行查询时,我的底层解析器返回null,我期待GraphQL这样 .

但是,我收到此错误:

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

发生这种情况是因为查询预期返回 ProfileProfile 必须具有 id 字段 .

但是,查询的返回类型不是非可空的 Profile! ,它是 Profile ,这意味着查询可能不会返回任何内容 .

如何正确解决这个问题?

2 回答

  • 0

    尝试在 Profiles 查询解析程序中返回 null . 如果你返回类似空对象的东西,Profile配置解析器会选择它并尝试将 undefined 作为 Profile.id 返回,正如你所提到的那样是一个模式错误 .

    尝试这样的事情:

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

    您的graphQL响应将看起来像这样

    {
      data: {
        profile: null
      }
    }
    
  • 0

    首先,您需要删除数据库并按原样使用 types.graphql

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

    部署它,错误将消失 .

    Main reason for happening this is you've already deployed data with not null thus it can't changed you need to drop our database, that's it

相关问题