Use GraphQL's List Type for Collections

Josh Black
InstructorJosh Black

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In order to handle collections of items in a GraphQL Schema, GraphQL has a List Type. In this video, we’ll learn the syntax for specifying a List of items in a GraphQL Schema.

[00:01] In the GraphQL schema that we built here, we have a field called video that returns explicitly a video type. While it's great that we're returning a specific type, sometimes it's necessary for us to query our GraphQL server for a collection or a list of a certain type.

[00:19] If we wanted to get a listing of all the videos that we may have, we add a field to our query type called videos. In order to note that this field returns a list of videos, we'll use these square brackets. Inside of the square brackets, we'll write down the type for video.

[00:39] What we've created here is a field called videos that returns a GraphQL list type of the video type. Now that we have this videos field defined, let's go and actually build out the collection of videos that will return from our resolvers.

[00:56] We'll create a variable called videoA that holds all the fields of a video type. We'll also go and create a video called videoB. Finally, we'll go and create our variable called videos that is just the collection of videoA and videoB.

[01:23] Now that we have our collection of videos, let's go and update our resolvers. Now we have a videos field, so we need to be able to tell our GraphQL schema how to actually resolve the videos field. So I'll add in videos, which will just be a function that will return our collection of videos.

[01:44] We can then update our query that we have down here by just changing a single letter instead of requesting the video field, we'll just request the videos field. For each of these fields that we have listed, it's actually going to go through our collection of videos and get the field for each individual video and return the results.

[02:06] We can verify this by running our query against our schema that we've defined and including our resolvers. If we switch into our terminal and run node index.js, we'll get a response which has the data field and it returns a collection of videos.