Skip to content

[bestpractices] Add connections best practice article #69

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 13, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions site/_core/swapiSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ interface Character {
# The friends of the character, or an empty list if they have none
friends: [Character]

# The friends of the character exposed as a connection with edges
friendsConnection(first: Int, after: ID): FriendsConnection!

# The movies this character appears in
appearsIn: [Episode]!
}
Expand Down Expand Up @@ -93,6 +96,9 @@ type Human implements Character {
# This human's friends, or an empty list if they have none
friends: [Character]

# The friends of the human exposed as a connection with edges
friendsConnection(first: Int, after: ID): FriendsConnection!

# The movies this human appears in
appearsIn: [Episode]!

Expand All @@ -111,13 +117,42 @@ type Droid implements Character {
# This droid's friends, or an empty list if they have none
friends: [Character]

# The friends of the droid exposed as a connection with edges
friendsConnection(first: Int, after: ID): FriendsConnection!

# The movies this droid appears in
appearsIn: [Episode]!

# This droid's primary function
primaryFunction: String
}

# A connection object for a character's friends
type FriendsConnection {
# The total number of friends
totalCount: Int

# The edges for each of the character's friends.
edges: [FriendsEdge]

# Information for paginating this connection
pageInfo: PageInfo!
}

# An edge object for a character's friends
type FriendsEdge {
# A cursor used for pagination
cursor: ID!

# The character represented by this friendship edge
node: Character
}

# Information for paginating this connection
type PageInfo {
hasNextPage: Boolean!
}

# Represents a review for a movie
type Review {
# The number of stars this review gave, 1-5
Expand Down Expand Up @@ -306,6 +341,14 @@ function getStarship(id) {
return starshipData[id];
}

function toCursor(str) {
return Buffer("cursor" + str).toString('base64');
}

function fromCursor(str) {
return Buffer.from(str, 'base64').toString().slice(6);
}

const resolvers = {
Query: {
hero: (root, { episode }) => getHero(episode),
Expand Down Expand Up @@ -349,13 +392,46 @@ const resolvers = {
return height;
},
friends: ({ friends }) => friends.map(getCharacter),
friendsConnection: ({ friends }, { first, after }) => {
first = first || friends.length;
after = parseInt(fromCursor(after), 10) || 0;
return {
edges: friends.map((friend, i) => ({
cursor: toCursor(i+1),
node: getCharacter(friend)
})).slice(after, first + after),
pageInfo: { hasNextPage: first + after < friends.length },
totalCount: friends.length
};
},
starships: ({ starships }) => starships.map(getStarship),
appearsIn: ({ appearsIn }) => appearsIn,
},
Droid: {
friends: ({ friends }) => friends.map(getCharacter),
friendsConnection: ({ friends }, { first, after }) => {
first = first || friends.length;
after = parseInt(fromCursor(after), 10) || 0;
return {
edges: friends.map((friend, i) => ({
cursor: toCursor(i+1),
node: getCharacter(friend)
})).slice(after, first + after),
pageInfo: { hasNextPage: first + after < friends.length },
totalCount: friends.length
};
},
appearsIn: ({ appearsIn }) => appearsIn,
},
FriendsConnection: {
edges: ({ edges }) => edges,
pageInfo: ({ pageInfo }) => pageInfo,
totalCount: ({ totalCount }) => totalCount,
},
FriendsEdge: {
node: ({ node }) => node,
cursor: ({ cursor }) => cursor,
},
Starship: {
length: ({ length }, { unit }) => {
if (unit === 'FOOT') {
Expand Down
1 change: 1 addition & 0 deletions site/learn/BestPractice-Authorization.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ title: Authorization
layout: ../_core/DocsLayout
category: Best Practices
permalink: /learn/authorization/
next: /learn/connections/
---

> Delegate authorization logic to the business logic layer
Expand Down
132 changes: 132 additions & 0 deletions site/learn/BestPractice-Connections.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
---
title: Connections
layout: ../_core/DocsLayout
category: Best Practices
permalink: /learn/connections/
---

> Different connection models enable different client capabilities

A common use case in GraphQL is traversing the relationship between sets of objects. There are a number of different ways that these relationships can be exposed in GraphQL, giving a varying set of capabilities to the client developer.

## Plurals

The most simple way to expose a connection between objects is with a field that returns a plural type. For example, if we wanted to get a list of R2-D2's friends, we could just ask for all of them:

```graphql
# { "graphiql": true }
{
hero {
name
friends {
name
}
}
}
```

## Slicing

Quickly, though, we realize that there are additional behaviors a client might want. A client might want to be able to specify how many friends they want to fetch; maybe they only want the first two. So we'd want to expose something like:


```graphql
{
hero {
name
friends(first:2) {
name
}
}
}
```

But if we just fetched the first two, we might want to paginate through the list as well; once the client fetches the first two friends, they might want to send a second request to ask for the next two friends. How can we enable that behavior.

## Pagination and Edges

There are a number of ways we could do pagination:

- We could do something like `friends(first:2 offset:2)` to ask for the next two in the list.
- We could do something like `friends(first:2 after:$friendId)`, to ask for the next two after the last friend we fetched.
- We could do something like `friends(first:2 after:$friendCursor)`, where we get a cursor from the last item and use that to paginate.

In general, we've found that **cursor-based pagination** is the most powerful of those designed. Especially if the cursors are opaque, either offset or ID-based pagination can be implemented using cursor-based pagination (by making the cursor the offset or the ID), and using cursors gives additional flexibility if the pagination model changes in the future. As a reminder that the cursors are opaque and that their format should not be relied upon, we suggest base64 encoding them.

That leads us to a problem; though; how do we get the cursor from the object? We wouldn't want cursor to live on the `User` type; it's a property of the connection, not of the object. So we want to introduce a new layer of indirection; our `friends` field should give us a list of edges, and an edge has both a cursor and the underlying node:

```graphql
{
hero {
name
friends(first:2) {
node {
name
}
cursor
}
}
}
```

The concept of an edge also proves useful if there is information that is specific to the edge, rather than to one of the objects. For example, if we wanted to expose "friendship time" in the API, having it live on the edge is a natural place to put it.

## End-of-list, counts, and Connections

Now we have the ability to paginate through the connection using cursors, but how do we know when we reach the end of the connection? We have to keep querying until we get an empty list back, but we'd really like for the connection to tell us when we've reached the end so we don't need that additional request. Similarly, what if we want to know additional information about the connection itself; for example, how many total friends does R2-D2 have?

To solve both of these problems, our `friends` field can return a connection object. The connection object will then have field for the edges, as well as other information (like total count and information about whether a next page exists). So our final query might look more like:


```graphql
{
hero {
name
friends(first:2) {
totalCount
edges {
node {
name
}
cursor
}
pageInfo {
hasNextPage
}
}
}
}
```

## Complete Connection Model

Clearly, this is more complex than our original design of just having a plural! But by adopting this design, we've unlocked a number of capabilities for the client:

- The ability to paginate through the list.
- The ability to ask for information about the connection itself, like `totalCount` or `pageInfo`.
- The ability to ask for information about the edge itself, like `cursor` or `friendshipTime`.
- The ability to change how our backend does pagination, since the user just uses opaque cursors.

To see this in action, there's an additional field in the example schema, called `friendsConnection`, that exposes all of these concepts. You can check it out in the example query. Try removing the `after` parameter to `friendsConnection` to see how the pagination will be affected.

```graphql
# { "graphiql": true }
{
hero {
name
friendsConnection(first:2 after:"Y3Vyc29yMQ==") {
totalCount
edges {
node {
name
}
cursor
}
pageInfo {
hasNextPage
}
}
}
}
```