-
Notifications
You must be signed in to change notification settings - Fork 2
/
cursor.go
114 lines (102 loc) · 2.23 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 model
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
)
type PermFilter struct {
AllowedFeeds []int
AllowedFeedVersions []int
}
func (pf *PermFilter) GetAllowedFeeds() []int {
if pf == nil {
return nil
}
return pf.AllowedFeeds
}
func (pf *PermFilter) GetAllowedFeedVersions() []int {
if pf == nil {
return nil
}
return pf.AllowedFeedVersions
}
type Cursor struct {
FeedVersionID int
ID int
Valid bool
}
func NewCursor(fvid int, id int) Cursor {
return Cursor{FeedVersionID: fvid, ID: id, Valid: true}
}
// UnmarshalJSON implements json.Marshaler interface.
func (r *Cursor) UnmarshalJSON(v []byte) error {
return r.Scan(v)
}
// MarshalJSON implements the json.marshaler interface.
func (r *Cursor) MarshalJSON() ([]byte, error) {
return json.Marshal(r.encode())
}
// UnmarshalGQL implements the graphql.Unmarshaler interface
func (r *Cursor) UnmarshalGQL(v interface{}) error {
return r.Scan(v)
}
// MarshalGQL implements the graphql.Marshaler interface
func (r Cursor) MarshalGQL(w io.Writer) {
b, _ := r.MarshalJSON()
w.Write(b)
}
// UnmarshalGQL implements the graphql.Unmarshaler interface
func (r *Cursor) Scan(value interface{}) error {
r.Valid = false
switch v := value.(type) {
case int64:
r.ID = int(v)
case int:
r.ID = v
case json.Number:
a, err := v.Int64()
if err != nil {
return err
}
r.ID = int(a)
case []byte:
return r.decode(string(v))
case string:
return r.decode(v)
case nil:
// ok
default:
return errors.New("invalid cursor")
}
r.Valid = true
return nil
}
func (r *Cursor) encode() string {
return base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%d,%d", r.FeedVersionID, r.ID)))
}
func (r *Cursor) decode(value string) error {
if len(value) == 0 {
return nil
}
dec, err := base64.RawURLEncoding.DecodeString(value)
if err != nil {
return errors.New("invalid cursor")
}
rawSplit := strings.Split(string(dec), ",")
if len(rawSplit) < 2 {
return errors.New("invalid cursor")
}
r.FeedVersionID, err = strconv.Atoi(rawSplit[0])
if err != nil {
return errors.New("invalid cursor")
}
r.ID, err = strconv.Atoi(rawSplit[1])
if err != nil {
return errors.New("invalid cursor")
}
return nil
}