GitHub provides the GraphQL explorer to play with GraphQL data and learn how to shape your queries. When your group of queries grows to the point of repeating objects and their fields, its time to move to fragments.
A fragment in GraphQL allows you to have:
- readability - a well-named fragment shortens queries and mutations
- reusability - reuse fragments in queries and mutations
- performance - on the client, fragments and their components are a cache layer
- type-safety - the code generator that builds your GraphQL SDK includes named fragments so you can access any deeply nested objects as fragments without the types and their guards you would need to manage
Typical places to create and use fragments to DRY up your GraphQL queries include the most common schema objects. For a GitHub GraphQL schema, those can include the User and Repository.
To get the entire list of repositories in a GitHub org, you need to compensate for the cursor/paging as well as the return results. An example query for that looks like:
$organization: String!
$pageSize: Int
$after: String
) {
organization(login: $organization) {
repositories(
after: $after
first: $pageSize
orderBy: { field: STARGAZERS, direction: DESC }
) {
totalCount
pageInfo {
startCursor
hasNextPage
endCursor
}
edges {
cursor
node {
...MyRepoFields
}
}
}
}
}
fragment MyRepoFields on Repository {
repositoryName: name
id
url
descriptionHTML
updatedAt
stargazers {
totalCount
}
forks {
totalCount
}
issues(states: [OPEN]) {
totalCount
}
pullRequests(states: [OPEN]) {
totalCount
}
}