首页 > 解决方案 > 可以是字符串或对象的值的Graphql标量类型?

问题描述

我有一个用于注册的 api,它返回字符串或 null 的错误,

error: 'Email already use' or error: null 

我如何在架构中构建它?我现在拥有的是:

const typeDefs = gql`
  type Mutation {
    signUp(email: String, password: String): String
  }
`;

由于 typeof null 是对象,我怎样才能在 graphql 中做到这一点?

signUp(email: String, password: String): String || Object

帮助?

标签: graphqlapollo-server

解决方案


GraphQL 具有返回错误值的标准语法,您的架构不需要直接考虑这一点。

在您的架构中,我将“无条件”返回您通常期望返回的任何类型:

type UserAccount { ... }
type Query {
  me: UserAccount # or null if not signed in
}
type Mutation {
  signUp(email: String!, password: String!): UserAccount!
}

如果不成功,您将返回一个空字段值(即使架构理论上声称它不应该)和一个错误。

{
  "errors": [
    {
      "message": "It didn’t work",
      "locations": [ { "line": 2, "column": 3 } ],
      "path": [ "signUp" ]
    }
  ]
}

推荐阅读