This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Use GraphQL's List Type for Collections

2:25 JavaScript lesson by

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.


egghead.io comment guidelines

Avatar
egghead.io

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.

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.

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.

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.

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.

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.

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?