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