Returning nested data

Let's make a far more complex query in this section. We'll search for a GitHub repository, return information about it, including the number of stars it has and the last issues that have been raised as a nested array:

  1. Let's start by entering the following query and executing it:
query { 
repository (owner:"facebook", name:"react") {
name
description
}
}

This time, we are asking for the repository object, but passing two parameters for the owner and name of the repository. We are asking for the name and description of the repository to be returned.

We see that the repository and fields we asked for are returned:

  1. Let's now request the number of stars against the repository. To do this, we ask for the totalCount field within the stargazers nested object:
query { 
repository (owner:"facebook", name:"react") {
name
description
stargazers {
totalCount
}
}
}

If we execute the query, we see these results returned:

  1. Let's now add an alias to totalCount within stargazers:
stargazers {
stars:totalCount
}

If we execute the query, we see the stars count is returned against the alias we specified:

{
"data": {
"repository": {
"name": "react",
"description": "A declarative, efficient, and flexible JavaScript library for building user interfaces.",
"stargazers": {
"stars": 114998
}
}
}
}
  1. Let's move on to requesting the last 5 issues within the repository:
{ 
repository (owner:"facebook", name:"react") {
name
description
stargazers {
stars:totalCount
}
issues(last: 5) {
edges {
node {
id
title
url
publishedAt
}
}
}
}
}

We request the issues object by passing 5 into the last parameter. We then request an edges object containing a node object that in turn contains the issue fields we are interested in.

So, what are the edges and node objects? Why can't we just request the fields we want directly? Well, this structure is in place to facilitate cursor-based pagination. 

If we execute the query, we get the last 5 issues included in our result.

So, GraphQL allows us to make a single web request for different bits of data returning just the fields we require. Doing a similar thing with the GitHub REST API would probably require multiple requests and we'd get a lot more data than we need returned to us. It is these types of queries where GraphQL shines over REST.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.127.197