Relay Cursor Connections (Pagination)

In this section, we continue the GraphQL example by explaining how to implement the Relay Cursor Connections Spec. If you’re not familiar with the Cursor Connections interface, read the following paragraphs that were taken from relay.dev:

In the query, the connection model provides a standard mechanism for slicing and paginating the result set.

In the response, the connection model provides a standard way of providing cursors, and a way of telling the client when more results are available.

An example of all four of those is the following query:

  1. {
  2. user {
  3. id
  4. name
  5. friends(first: 10, after: "opaqueCursor") {
  6. edges {
  7. cursor
  8. node {
  9. id
  10. name
  11. }
  12. }
  13. pageInfo {
  14. hasNextPage
  15. }
  16. }
  17. }
  18. }

Clone the code (optional)

The code for this tutorial is available under github.com/a8m/ent-graphql-example, and tagged (using Git) in each step. If you want to skip the basic setup and start with the initial version of the GraphQL server, you can clone the repository and checkout v0.1.0 as follows:

  1. git clone git@github.com:a8m/ent-graphql-example.git
  2. cd ent-graphql-example
  3. go run ./cmd/todo/

Add Annotations To Schema

Ordering can be defined on any comparable field of ent by annotating it with entgql.Annotation. Note that the given OrderField name must match its enum value in GraphQL schema (see next section below).

  1. func (Todo) Fields() []ent.Field {
  2. return []ent.Field{
  3. field.Text("text").
  4. NotEmpty().
  5. Annotations(
  6. entgql.OrderField("TEXT"),
  7. ),
  8. field.Time("created_at").
  9. Default(time.Now).
  10. Immutable().
  11. Annotations(
  12. entgql.OrderField("CREATED_AT"),
  13. ),
  14. field.Enum("status").
  15. NamedValues(
  16. "InProgress", "IN_PROGRESS",
  17. "Completed", "COMPLETED",
  18. ).
  19. Default("IN_PROGRESS").
  20. Annotations(
  21. entgql.OrderField("STATUS"),
  22. ),
  23. field.Int("priority").
  24. Default(0).
  25. Annotations(
  26. entgql.OrderField("PRIORITY"),
  27. ),
  28. }
  29. }

Define Types In GraphQL Schema

Next, we need to define the ordering types along with the Relay Connection Types in the GraphQL schema:

  1. # Define a Relay Cursor type:
  2. # https://relay.dev/graphql/connections.htm#sec-Cursor
  3. scalar Cursor
  4. type PageInfo {
  5. hasNextPage: Boolean!
  6. hasPreviousPage: Boolean!
  7. startCursor: Cursor
  8. endCursor: Cursor
  9. }
  10. type TodoConnection {
  11. totalCount: Int!
  12. pageInfo: PageInfo!
  13. edges: [TodoEdge]
  14. }
  15. type TodoEdge {
  16. node: Todo
  17. cursor: Cursor!
  18. }
  19. # These enums are matched the entgql annotations in the ent/schema.
  20. enum TodoOrderField {
  21. CREATED_AT
  22. PRIORITY
  23. STATUS
  24. TEXT
  25. }
  26. enum OrderDirection {
  27. ASC
  28. DESC
  29. }
  30. input TodoOrder {
  31. direction: OrderDirection!
  32. field: TodoOrderField
  33. }

Note that the naming must take the form of <T>OrderField / <T>Order for autobinding to the generated ent types. Alternatively @goModel directive can be used for manual type binding.

Add Pagination Support For Query

  1. type Query {
  2. todos(
  3. after: Cursor
  4. first: Int
  5. before: Cursor
  6. last: Int
  7. orderBy: TodoOrder
  8. ): TodoConnection
  9. }

That’s all for the GraphQL schema changes, let’s run gqlgen code generation.

Update The GraphQL Resolver

After changing our Ent and GraphQL schemas, we’re ready to run the codegen and use the Paginate API:

  1. go generate ./...

Head over to the Todos resolver and update it to pass orderBy argument to .Paginate() call:

  1. func (r *queryResolver) Todos(ctx context.Context, after *ent.Cursor, first *int, before *ent.Cursor, last *int, orderBy *ent.TodoOrder) (*ent.TodoConnection, error) {
  2. return r.client.Todo.Query().
  3. Paginate(ctx, after, first, before, last,
  4. ent.WithTodoOrder(orderBy),
  5. )
  6. }

Pagination Usage

Now, we’re ready to test our new GraphQL resolvers. Let’s start with creating a few todo items by running this query multiple times (changing variables is optional):

  1. mutation CreateTodo($todo: TodoInput!) {
  2. createTodo(todo: $todo) {
  3. id
  4. text
  5. createdAt
  6. priority
  7. parent {
  8. id
  9. }
  10. }
  11. }
  12. # Query Variables: { "todo": { "text": "Create GraphQL Example", "status": "IN_PROGRESS", "priority": 1 } }
  13. # Output: { "data": { "createTodo": { "id": "2", "text": "Create GraphQL Example", "createdAt": "2021-03-10T15:02:18+02:00", "priority": 1, "parent": null } } }

Then, we can query our todo list using the pagination API:

  1. query {
  2. todos(first: 3, orderBy: {direction: DESC, field: TEXT}) {
  3. edges {
  4. node {
  5. id
  6. text
  7. }
  8. cursor
  9. }
  10. }
  11. }
  12. # Output: { "data": { "todos": { "edges": [ { "node": { "id": "16", "text": "Create GraphQL Example" }, "cursor": "gqFpEKF2tkNyZWF0ZSBHcmFwaFFMIEV4YW1wbGU" }, { "node": { "id": "15", "text": "Create GraphQL Example" }, "cursor": "gqFpD6F2tkNyZWF0ZSBHcmFwaFFMIEV4YW1wbGU" }, { "node": { "id": "14", "text": "Create GraphQL Example" }, "cursor": "gqFpDqF2tkNyZWF0ZSBHcmFwaFFMIEV4YW1wbGU" } ] } } }

We can also use the cursor we got in the query above to get all items after that cursor:

  1. query {
  2. todos(first: 3, after:"gqFpEKF2tkNyZWF0ZSBHcmFwaFFMIEV4YW1wbGU", orderBy: {direction: DESC, field: TEXT}) {
  3. edges {
  4. node {
  5. id
  6. text
  7. }
  8. cursor
  9. }
  10. }
  11. }
  12. # Output: { "data": { "todos": { "edges": [ { "node": { "id": "15", "text": "Create GraphQL Example" }, "cursor": "gqFpD6F2tkNyZWF0ZSBHcmFwaFFMIEV4YW1wbGU" }, { "node": { "id": "14", "text": "Create GraphQL Example" }, "cursor": "gqFpDqF2tkNyZWF0ZSBHcmFwaFFMIEV4YW1wbGU" }, { "node": { "id": "13", "text": "Create GraphQL Example" }, "cursor": "gqFpDaF2tkNyZWF0ZSBHcmFwaFFMIEV4YW1wbGU" } ] } } }

Great! With a few simple changes, our application now supports pagination! Please continue to the next section where we explain how to implement GraphQL field collections and learn how Ent solves the “N+1 problem” in GraphQL resolvers.