Use GraphQL's Object Type for Basic Types

Josh Black
InstructorJosh Black

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

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.

[00:00] 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.

[00:13] 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.

[00:35] 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.

[00:49] 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.

[01:16] 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.

[01:23] 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.

[01:44] 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.

[01:59] 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.

Bryce Fischer
Bryce Fischer
~ 2 years ago

The branches for code in GitHub all go to 404 pages...