This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Use GraphQL's Object Type for Basic Types

2:13 JavaScript lesson by

We can create the most basic components of our GraphQL Schema using GraphQL's Object Types. These types allow us to group related fields together under a specific type, such as a Video or a User, and then allows us to fetch these types when we query our schema. In this video, we'll learn how to write GraphQL Object Types in GraphQL's Schema language, as well as how to create resolvers for them, and ultimately how to query them.


egghead.io comment guidelines

Avatar
egghead.io

We can create the most basic components of our GraphQL Schema using GraphQL's Object Types. These types allow us to group related fields together under a specific type, such as a Video or a User, and then allows us to fetch these types when we query our schema. In this video, we'll learn how to write GraphQL Object Types in GraphQL's Schema language, as well as how to create resolvers for them, and ultimately how to query them.

I have the schema right now where all we have is the schema type, as well as the query type. Sitting on the query type is a bunch of ad hoc fields that we have here that are just basic GraphQL primitive types.

Really, none of these fields relate to the query type itself. Instead, all of these fields relate to a video type. Instead of having a type query here, we can actually make a GraphQL object type called "type video," and we grab all of these fields and place them on the video type.

Now, instead of having our type query contain all of those fields, we can instead have video as the field that someone will query and what it will return is the video type.

Now, we can actually go and update the resolvers that we have for the schema, and instead of returning a function for each of the fields that we have, we can actually have a video field. What this is going to return is an object. This object has an ID field, it has a title field, it has a duration field, and then finally it has a watch field.

We can go and actually delete all of the resolvers that we have for the other fields that used to live on the query type.

With this new video resolver defined, let's go and update our query that we had. Instead of querying the fields directly, now, we're going to be querying the video field. The video field is a video object type. We query for fields on that object type using these curly braces.

On video, we know that we have an ID that we can query for, as well as a title, duration, and watch fields that we can also query for. Now, we can use GraphQL to actually resolve our query.

If we hop into our terminal and run node index.js and hit Enter, we actually get our response from our GraphQL server with our video field and all of the fields that we requested on that type.

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