-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpaginator.go
106 lines (85 loc) · 2.08 KB
/
paginator.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
package go_paginate
import (
"encoding/base64"
"github.com/raphaelvigee/go-paginate/cursor"
"github.com/raphaelvigee/go-paginate/driver"
)
type PageInfo struct {
HasNextPage bool `json:"hasNextPage"`
HasPreviousPage bool `json:"hasPreviousPage"`
StartCursor string `json:"startCursor"`
EndCursor string `json:"endCursor"`
}
type Page struct {
driver.Executor
PageInfo
CursorFunc func(i int64) (string, error)
}
func (p Page) Cursor(i int64) (string, error) {
return p.CursorFunc(i)
}
type Options struct {
driver.Driver
// Will default to cursor.Chain(cursor.MsgPack(), cursor.Base64(base64.StdEncoding))
CursorMarshaller cursor.Marshaller
}
func New(o Options) *Paginator {
p := &Paginator{Options: o}
if p.CursorMarshaller == nil {
p.CursorMarshaller = cursor.Chain(cursor.MsgPack(), cursor.Base64(base64.StdEncoding))
}
return p
}
type Paginator struct {
Options
}
func (p *Paginator) Cursor(encoded string, typ cursor.Type, limit int) (cursor.Cursor, error) {
data, err := p.CursorMarshaller.Unmarshal([]byte(encoded))
if err != nil {
return cursor.Cursor{}, err
}
value, err := p.Driver.CursorDecode(data)
if err != nil {
return cursor.Cursor{}, err
}
return cursor.Cursor{
Type: typ,
Limit: limit,
Value: value,
}, nil
}
func (p *Paginator) Paginate(c cursor.Cursor, input interface{}) (Page, error) {
dp, err := p.Driver.Paginate(c, input)
if err != nil {
return Page{}, err
}
info := dp.Info()
sc, err := p.CursorMarshaller.Marshal(info.StartCursor)
if err != nil {
return Page{}, err
}
ec, err := p.CursorMarshaller.Marshal(info.EndCursor)
if err != nil {
return Page{}, err
}
return Page{
Executor: dp,
PageInfo: PageInfo{
HasNextPage: info.HasNextPage,
HasPreviousPage: info.HasPreviousPage,
StartCursor: string(sc),
EndCursor: string(ec),
},
CursorFunc: func(i int64) (string, error) {
rc, err := dp.Cursor(i)
if err != nil {
return "", err
}
m, err := p.CursorMarshaller.Marshal(rc)
if err != nil {
return "", err
}
return string(m), nil
},
}, nil
}