Cursor is a generic implementation of the Relay Cursor Connections Specification. It is a simple library that can be used to paginate any list of items.
Simply run the following command to get the package and start using it:
go get github.com/asger-noer/go-cursor
You can create a new connection by providing a list of items and a cursor function that can be used to get the cursor for each item. You can also provide a list of arguments to the connection to specify the pagination.
args := []cursor.Argument{
cursor.First(10),
cursor.After("MQ=="),
}
// Create a new connection with the list of users
cur, err := cursor.New(users, userCursor, args...)
if err != nil {
// Handle error
}
// pageinfo contains information about the current page
pageinfo := cur.PageInfo()
// Edges contains the list of items in the current page
edges := cur.Edges() {
Tip
You can find a complete example of how to use Cursor with gqlgen in the examples/gqlgen directory.
If you are using gqlgen, you can use the Cursor
type to generate the cursor for each item. You'll need to define the concrete implementation of the Connection
and Edge
types with the model being paginated. This is done by adding creating a type and binding it in the model section of the gqlgen.yml
file:
types.go:
package types
import (
"github.com/asger-noer/go-cursor"
"github.com/asger-noer/go-cursor/examples/gqlgen/graph/model"
)
type (
TodoConnection = cursor.Connection[model.Todo]
TodoEdge = cursor.Edge[model.Todo]
)
gqlgen.yml:
models:
PageInfo:
model:
- github.com/asger-noer/go-cursor.PageInfo
TodoConnection:
model:
- examples/gqlgen/graph/types.TodoConnection
TodoEdge:
model:
- examples/gqlgen/graph/types.TodoEdge