什么是 GraphQL 中的叹号?

在模式文件中,我注意到在一些类型后面有感叹号,比如

# Information on an account relationship
type AccountEdge {
cursor: String!
node: Account!
}

- 这些是什么意思?-我在文档或者谷歌上都找不到任何相关信息

39582 次浏览

这意味着字段是不可为空的。

Graphql-模式和类型中查看更多信息

来自 规格:

默认情况下,GraphQL 中的所有类型都可以为空; 空值对于上述所有类型都是有效的响应。若要声明不允许 Null 的类型,可以使用 GraphQL Non-Null 类型。此类型包装基础类型,此类型的作用与该包装类型相同,但 null 不是包装类型的有效响应。后面的叹号表示使用非空类型的字段,如下所示: name: String!.

换句话说,GraphQL 中的类型在默认情况下是可空的。类型后面的叹号特别指定该类型为不可为空。

这取决于使用类型的位置,具有不同的含义。

输出

当对 场地的类型应用非空时,这意味着如果服务器将该字段解析为 null,则响应将失败验证。只要错误不是 propagate all the way up to the root,您仍然可能收到部分响应。

例如,给定如下模式:

type Query {
user: User
}


type User {
id: ID!
}

这里的 id字段是非空的。通过将字段标记为非空,我们实际上是 保证,我们将永远不会为这个字段返回空。如果服务器确实返回 null,那么这表明出现了严重错误,我们希望抛出验证错误。

输入

当非空应用于 输入的类型时,比如参数、输入对象字段或变量,它使该输入成为必需的。例如:

type Query {
getUser(id: ID!, status: Status): User
}

在这里,id参数是非空的。如果我们请求 getUser字段,我们将总是必须为它提供 id参数。另一方面,因为 status参数是可空的,所以它是可选的,可以省略。这也适用于变量:

query MyQuery ($foo: ID!) {
getUser(id: $foo)
}

因为 $foo变量是非空的,当您发送查询时,它不能被忽略,它的值不能等于 null

关于变量类型的特殊说明

因为在我们的示例中,id字段是非空 ID(即 ID!)类型,所以我们传递给它的任何变量都必须是非空 ID。如果我们的 $foo变量是一个可空的 ID,我们就不能将它传递给 id参数。然而,事实并非如此。如果一个参数可以为空,则 可以传递给它一个非空变量。

换句话说:

+----------+----------+--------+
| Argument | Variable | Valid? |
+----------+----------+--------+
| String   | String   |   ✅   |
| String   | String!  |   ✅   |
| String!  | String   |   ❌   |
| String!  | String!  |   ✅   |
+----------+----------+--------+

TLDR: 表示如果 value 为 null 则抛出错误

用户尝试发送一个输入字段 null,该字段具有 !-> 即时错误响应

服务器试图为返回 !-> 错误的字段返回 null

如果 !只抛出错误,为什么要添加它?

如果您知道输入中的 null会使服务器崩溃,那么最好尽早抛出错误。

If you know that a null in the response would crash your client then better to throw the error early.

我使用的“崩溃”是指所有可能发生的 bug 或易变性。

例子

Schema:

type Query
{
data(input: InputType!): ResponseType!
}


input InputType
{
inputField: String!
}


type ResponseType
{
field: String!
}

可以输入的变量:

{
input: {
inputField: "sample text"
}
}

将抛出错误的输入变量:

// error: inputField is null
{
input: {
inputField: null
}
}


// error: inputField is null (because it's missing)
{
input: {
}
}


// error: input is null
{
input:  null
}


// error: input is null (because it's missing)
{
}

服务器响应正常:

{
data: {
field: "sample text"
}
}

将抛出错误的服务器响应:

// error: field is null
{
data: {
field: null
}
}


// error: field is null (because it's missing)
{
data: {
}
}


// error: data is null
{
data: null
}