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