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