Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - GraphQL: Non-nullable array/list

I'm learning GraphQL now and while walking through tutorial I met behavior that I can't understand. Let's say we have defined type in schema:

type Link {
  id: ID!
  url: String!
  description: String!
  postedBy: User
  votes: [Vote!]!
}

Due to docs votes: [Vote!]! means that that field should be a non-nullable and array itself should be non-nullable too. But just after that author of tutorial shows example of query and for some of links it returns empty array for votes field. Like this:

{
 "url": "youtube.com",
 "votes": []
},
{
 "url": "agar.io",
 "votes": []
}

So my question is: Doesn't "non-nullable" means "empty" in graphQL schema or it's just some kind of wrong behavior of graphQL server (I mean it returns array of nothing without warning that there should be something due to schema).

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Non-null means exactly what it sounds like -- not null. An empty array is not null -- it's still returning a value.

Here is a summary table:

declaration accepts: | null | []   | [null] | [{foo: 'BAR'}]
------------------------------------------------------------------------
[Vote!]!             | no   | yes  | no     | yes
[Vote]!              | no   | yes  | yes    | yes
[Vote!]              | yes  | yes  | no     | yes
[Vote]               | yes  | yes  | yes    | yes

[Vote!]! means that the field (in this case votes) cannot return null and that it must resolve to an array and that none of the individuals items inside that array can be null. So [] and [{}] and [{foo: 'BAR'}] would all be valid (assuming foo is non-null). However, the following would throw: [{foo: 'BAR'}, null]

[Vote]! means that the field cannot return null, but any individual item in the returned list can be null.

[Vote!] means that the entire field can be null, but if it does return a value, it needs to an array and each item in that array cannot be null.

[Vote] means that the entire field can be null, but if it does return a value, it needs to an array. However, any member of the array may also be null.

If you need to verify whether an array is empty, you have to do so within your resolver logic. If you want GraphQL to still throw when an array is empty, just have your resolver return a rejected Promise.

For more information your can read the list and non-null section of the GraphQL introduction or take a look at the spec.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...