可以是字符串或对象的值的 Graphql 标量类型?

Graphql scalar type for a value that can be string or object?

我有一个 api 用于注册,其中 returns 字符串错误或空值,

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

帮忙?

在 GraphQL 中,您可以定义哪些字段可以 null 哪些不能。 看看文档: https://graphql.org/learn/schema/#object-types-and-fields

String is one of the built-in scalar types - these are types that resolve to a single scalar object, and can't have sub-selections in the query. We'll go over scalar types more later.

String! means that the field is non-nullable, meaning that the GraphQL service promises to always give you a value when you query this field. In the type language, we'll represent those with an exclamation mark.

因此,如果您的模式字符串绝对没问题。可以为空

type Mutation {
  signUp(email: String, password: String): String
}

GraphQL 有一个 standard syntax for returning error values,您的模式不需要直接考虑这个。

在你的架构中,我会“无条件地”return你通常期望的任何类型 return:

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" ]
    }
  ]
}