1. 16
    Build a GraphQL Query with Exactly the Data you need for a Posts Page
    1m 26s

Build a GraphQL Query with Exactly the Data you need for a Posts Page

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

The benefit of GraphQL is to have all the data you need in one request, with nothing more or less.

If you had a REST API, you would typically receive the entire object back in your response. This leads to over fetching and can result in performance issues. With GraphQL, you only receive the data you explicitly request.

In this lesson, we will build a GraphQL query that queries only the essential data needed on the front end to display a post.

Instructor: [0:00] The benefit of using GraphQL is that we can make a single query where multiple queries might have been necessary with REST API. Let's gather all the information for our post. With all posts, and the nodes in the post.

[0:12] For each post we want the author, and specifically from that author, let's get their name and their nice name. Maybe you'll want their ID, and why not get their avatar, just so that we can maybe make a picture for them. We might blocks.

[0:25] I'm going to stick with content for the moment. The date, the length, the title and the URI. I also care about comments, so let's have a look at comments. I want all the nodes within the comments. I want the author's node, specifically their name, and maybe their email.

[0:38] I want the date the comment was made, so I can sort out the other content. I've crafted this GraphQL query. Previously I had to alter the REST API or do another call, in order to get this data on the REST API. Similar with the comments, I had to either alter the API or do another call. The other benefit is that I'm only asking for the things I might use.

[1:00] If I choose not to use any of these fields in my frontend, I can remove them from the query. I'm going to have the Avatar link so I can make a picture. I've got my slug, my content, my comments and also the author details.

[1:14] This query could get quite large, because we might have the individual blocks that we've exposed as well for requesting exactly the data we want, no more and no less. It means the data traveling over the wire is as small as possible.