connections.go

 1//go:generate genny -in=connection_template.go -out=gen_bug.go gen "NodeType=string EdgeType=LazyBugEdge ConnectionType=models.BugConnection"
 2//go:generate genny -in=connection_template.go -out=gen_operation.go gen "NodeType=bug.Operation EdgeType=models.OperationEdge ConnectionType=models.OperationConnection"
 3//go:generate genny -in=connection_template.go -out=gen_comment.go gen "NodeType=bug.Comment EdgeType=models.CommentEdge ConnectionType=models.CommentConnection"
 4
 5// Package connections implement a generic GraphQL relay connection
 6package connections
 7
 8import (
 9	"encoding/base64"
10	"fmt"
11	"strconv"
12	"strings"
13)
14
15const cursorPrefix = "cursor:"
16
17// Edge define the contract for an edge in a relay connection
18type Edge interface {
19	GetCursor() string
20}
21
22// OffsetToCursor create the cursor string from an offset
23func OffsetToCursor(offset int) string {
24	str := fmt.Sprintf("%v%v", cursorPrefix, offset)
25	return base64.StdEncoding.EncodeToString([]byte(str))
26}
27
28// CursorToOffset re-derives the offset from the cursor string.
29func CursorToOffset(cursor string) (int, error) {
30	str := ""
31	b, err := base64.StdEncoding.DecodeString(cursor)
32	if err == nil {
33		str = string(b)
34	}
35	str = strings.Replace(str, cursorPrefix, "", -1)
36	offset, err := strconv.Atoi(str)
37	if err != nil {
38		return 0, fmt.Errorf("Invalid cursor")
39	}
40	return offset, nil
41}