GraphQL 规范列表和 NonNull 说明

GraphQL spec List and NonNull clarification

我在解释 GraphQL 规范的这一部分时遇到了一些问题。

https://facebook.github.io/graphql/#sec-Combining-List-and-Non-Null

1.

If the modified type of a List is Non‐Null, then that List may not contain any null items.

2.

If the modified type of a Non‐Null is List, then null is not accepted, however an empty list is accepted.

我假设这些代表是

  1. 列表[类型!]
  2. 列表[类型]!

假设这么多是正确的。

第一个问题:对于 1,规范没有明确说明空列表是无效的,应该吗?

This test 在 graphql-js 项目中建议它不应该。

如果是这样,规范中没有指定非空列表的内容吗?

第二个问题: 如果没有修饰符 (1),我是否可以提交具有空值的列表(如下所示)?

List[Book]

Book
title: String!

createBook(input: {books: [{null, {title: "Book a"}}]})

GraphiQL 似乎不允许将 null 添加到列表中,无论修饰符是否存在。这会是 GraphiQL 中的错误吗?

你猜对了。有four possible combinations:

[字符串]

null // valid
[] // valid
['a', 'b'] // valid
['a', null, 'b'] // valid

[字符串!]

null // valid
[] // valid
['a', 'b'] // valid
['a', null, 'b'] // invalid

[字符串]!

null // invalid
[] // valid
['a', 'b'] // valid
['a', null, 'b'] // valid

[字符串!]!

null // invalid
[] // valid
['a', 'b'] // valid
['a', null, 'b'] // invalid

First question: For 1, the spec doesn't explicitly say empty lists are invalid, should it?

不必。默认情况下,GraphQL 中的所有类型都可以为空,包括列表。以上第一个例子适用。

Second question: Without the modifier (1) should I be able to submit a List with null values (like below)?

是的。 GraphQL spec section 5.3.3 声明参数必须与架构中定义的类型兼容。

但是在实践中,发送包含空元素的列表是没有用的。这可能就是 GraphiQL 不支持它的原因。


旁注:关于何时使用不可空类型,this article 可以增加一些关于为什么在 GraphQL 中使用可空类型的观点 API 可能是一个不错的选择,即使该字段不应为空。