-
Notifications
You must be signed in to change notification settings - Fork 323
/
cursor.go
114 lines (97 loc) · 2.61 KB
/
cursor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package clickhouse
import (
"encoding/base64"
"fmt"
"strings"
"time"
e "github.com/pkg/errors"
modelInputs "github.com/highlight-run/highlight/backend/private-graph/graph/model"
)
type Edge[T interface{}] struct {
Cursor string
Node *T
}
type Connection[T interface{}] struct {
Edges []*Edge[T]
PageInfo *modelInputs.PageInfo
}
func getConnection[T interface{}](edges []*Edge[T], pagination Pagination) *Connection[T] {
var (
endCursor string
startCursor string
hasNextPage bool
hasPreviousPage bool
)
if pagination.At != nil && len(*pagination.At) > 1 {
idx := getCursorIdx(edges, *pagination.At)
beforeCount := idx
afterCount := len(edges) - idx - 1
if beforeCount == LogsLimit/2+1 { // has backwards pagination
hasPreviousPage = true
edges = edges[1:] // remove first
}
if afterCount == LogsLimit/2+1 { // has forward pagination
hasNextPage = true
edges = edges[:len(edges)-1] // remove last
}
} else if pagination.After != nil && len(*pagination.After) > 1 {
hasPreviousPage = true // implicitly true because the passed in cursor should match
if len(edges) >= LogsLimit+1 {
hasNextPage = true
edges = edges[:len(edges)-1]
}
} else if pagination.Before != nil && len(*pagination.Before) > 1 {
hasNextPage = true // implicitly true because the passed in cursor should match
if len(edges) >= LogsLimit+1 {
hasPreviousPage = true
edges = edges[1 : len(edges)-1]
}
} else {
if len(edges) >= LogsLimit+1 { // has forward page
hasNextPage = len(edges) == LogsLimit+1
edges = edges[:LogsLimit]
}
}
if len(edges) > 0 {
startCursor = edges[0].Cursor
endCursor = edges[len(edges)-1].Cursor
}
return &Connection[T]{
Edges: edges,
PageInfo: &modelInputs.PageInfo{
HasNextPage: hasNextPage,
HasPreviousPage: hasPreviousPage,
EndCursor: endCursor,
StartCursor: startCursor,
},
}
}
func getCursorIdx[T interface{}](edges []*Edge[T], cursor string) int {
for idx, edge := range edges {
if edge.Cursor == cursor {
return idx
}
}
return -1
}
func encodeCursor(t time.Time, uuid string) string {
key := fmt.Sprintf("%s,%s", t.Format(time.RFC3339), uuid)
return base64.StdEncoding.EncodeToString([]byte(key))
}
func decodeCursor(encodedCursor string) (timestamp time.Time, uuid string, err error) {
byt, err := base64.StdEncoding.DecodeString(encodedCursor)
if err != nil {
return
}
arrStr := strings.Split(string(byt), ",")
if len(arrStr) != 2 {
err = e.New("cursor is invalid")
return
}
timestamp, err = time.Parse(time.RFC3339, arrStr[0])
if err != nil {
return
}
uuid = arrStr[1]
return
}