Introduction to GraphQL Validations: Non Nullable & List
This course has been updated! We now recommend you take the Server-Side GraphQL in Node.js course.
Transcript from the "Validations: Non Nullable & List" Lesson
>> Speaker 1: Object type fields also describe any arguments and/or validations. So you saw me do one of those before on age, I had this little exclamation point here, like that. That's a validation, that's literally the only validation that GraphQL's gonna give you, and that means it's required. That means if the query asks for this field called age, and it comes back null, throw an error.
[00:00:24] It's a non-null field. It has to be there. So that's what that means. Other things, other enhancements that you can do to add to fields is, if you want this to be a list. So let's say, instead of having a best friend, we have best friends and I want it to be a list of cats.
[00:00:41] What I can do is I can wrap this in an array, like this. Now this must be an array of cats, so now, when I ask your best friends, I better get back an array, and inside it, there better be cat objects. And then the same thing applies for validations.
[00:00:56] I can add validations saying that it must be an array, as in the array must be there. Then I can also add a validation to say not only is the array must be there, but it must have a cat in it. Yes?
>> Speaker 2: But if you send back just one object, will it consider that to be a one object array?
>> Speaker 1: It depends on what GraphQL server you're using. Some GraphQL servers will get smart and they're like okay I'll just wrap this in an array for you, so like, whatever. But some are really strict and they're like, no.
>> Speaker 2: So you better just do it?
>> Speaker 1: You better just do it, yeah.
[00:01:29] Yeah, cuz like I said, it really depends on the implementation of the server. I think Apollo server's really strict by default, it's like, no, that's not an array. But some servers I've seen will try to coerce for you like, I'll coerce this to a number for you, even though you said it was a string or vice versa.
[00:01:45] I don't really like that. I like to just be strict. I like to be the way that I said it was supposed to be. That way, I can guarantee what I'm doing. And then the types are the target for all of the requests. Right, so if we make a request, at the end of the day if we look at the schema, we're trying to get a type.
[00:02:02] So for the myCat query, I'm trying to get a cat type. For the Hello query, I'm trying to get a string. That is the whole point of a request, a query that's coming in, is to get a type. That is the objective of a GraphQL, is to resolve types.
[00:02:16] That is its job. And the objective of a query is to get the types in the formatted way that you describe, that's allowed to you by the schema. So that's the job. Types are the target of all requests.