forked from lokalise/go-lokalise-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagination.go
89 lines (73 loc) · 1.92 KB
/
pagination.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
package lokalise
import (
"net/http"
"strconv"
"github.com/go-resty/resty/v2"
"github.com/google/go-querystring/query"
)
const (
PaginationOffset = "offset"
PaginationCursor = "cursor"
)
type PageCounter interface {
NumberOfPages() int64
CurrentPage() int64
}
type CursorPager interface {
HasNextCursor() bool
NextCursor() string
}
type Paged struct {
TotalCount int64 `json:"-"`
PageCount int64 `json:"-"`
Limit int64 `json:"-"`
Page int64 `json:"-"`
Cursor string `json:"-"`
}
func (p Paged) NumberOfPages() int64 {
return p.PageCount
}
func (p Paged) CurrentPage() int64 {
return p.Page
}
func (p Paged) NextCursor() string { return p.Cursor }
func (p Paged) HasNextCursor() bool { return p.Cursor != "" }
type OptionsApplier interface {
Apply(req *resty.Request)
}
type PageOptions struct {
Pagination string `url:"pagination,omitempty"`
Limit uint `url:"limit,omitempty"`
Page uint `url:"page,omitempty"`
Cursor string `url:"cursor,omitempty"`
}
func (options PageOptions) Apply(req *resty.Request) {
v, _ := query.Values(options)
req.SetQueryString(v.Encode())
}
const (
headerTotalCount = "X-Pagination-Total-Count"
headerPageCount = "X-Pagination-Page-Count"
headerLimit = "X-Pagination-Limit"
headerPage = "X-Pagination-Page"
headerNextCursor = "X-Pagination-Next-Cursor"
)
func applyPaged(res *resty.Response, paged *Paged) {
headers := res.Header()
paged.Limit = headerInt64(headers, headerLimit)
paged.TotalCount = headerInt64(headers, headerTotalCount)
paged.PageCount = headerInt64(headers, headerPageCount)
paged.Page = headerInt64(headers, headerPage)
paged.Cursor = headers.Get(headerNextCursor)
}
func headerInt64(headers http.Header, headerKey string) int64 {
headerValue := headers.Get(headerKey)
if headerValue == "" {
return -1
}
value, err := strconv.ParseInt(headers.Get(headerKey), 10, 64)
if err != nil {
return -1
}
return value
}