Skip to main content

Connections in GraphQL

· 3 min read
Alex Weinle
GraphQL Developer and AWS Architect

What's a Connection?

A phrase used in the graphQL best practices is thinking in graphs, part of which is the ability to access children (and children of children) of the record that you retrieve. As an example, in the Legalesign schema, a User can belong to many Groups as seen from the user point of view, or seen from the group point of view a Group can have many User child records.

These many-to-one and many-to-many relations will probably be familiar to you if you're used to relational databases, like MySQL, SQL Server or Oracle. With a traditional database they would be represented by a foreign key or a join table or associative entity.

This way to access child records is referred to as a Connection in graphql lingo - and this blog aims to demystify them for you.

It may be useful for you to go to Legalesign GraphQL Explorer and log in with your credentials, so that you can test out what we explore in each section.

Using a Connection in GraphQL

You'll notice in the explorer that every Connection type has a field that exposes all the items in the collection (assuming that you didn't limit the number of records in the query or that there aren't so many that it hits the default limitation of the API which stops fetching records at 900). In GroupConnection this is the 'groups' field.

That's great isn't it! Why would anyone bother with Edge and Nodes? Well, in order to understand that let's think about edges in a little more detail.

note

You can use the plural field if you're certain that you want all the records available without pagination and know they won't exceed the 900 cap.

Making Friends with the Edge

The Edge, our friend

The terminology of graphql is mathematical, because graphs themselves are, well, mathy. So many terms, such as Node and Edge are borrowed from that field. You probably recall nodes as points on shapes, and edges are lines that connect them. Our schema's idea of an Edge is similar in that it is a good way to describe the relation between any two of our types, like a User and a Group.

Instead of saying two types are related, an Edge can supply us with additional information, such as which permissions a User has in a Group.

query OrganisationExpiringItems {
retention2030: organisation(
id: "b3JnNTdjYWRjNmEtM2RmZC00MzA3LTk1MWEtOGVlNmIwOGVlYTg1"
) {
id
name
retentionConnection(
first: 500
start: "2020-11-01T08:00:00Z"
end: "2030-11-01T08:00:00Z"
) {
totalCount
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
edges {
node {
id
organisation
group
location
ttl
completed
}
cursor
}
}
}
}