connections.go

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