forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
paging.go
104 lines (87 loc) · 2 KB
/
paging.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
package influxdb
import (
"net/url"
"strconv"
)
const (
DefaultPageSize = 20
MaxPageSize = 100
)
// PagingFilter represents a filter containing url query params.
type PagingFilter interface {
// QueryParams returns a map containing url query params.
QueryParams() map[string][]string
}
// PagingLinks represents paging links.
type PagingLinks struct {
Prev string `json:"prev,omitempty"`
Self string `json:"self"`
Next string `json:"next,omitempty"`
}
// FindOptions represents options passed to all find methods with multiple results.
type FindOptions struct {
Limit int
Offset int
SortBy string
Descending bool
}
// QueryParams returns a map containing url query params.
func (f FindOptions) QueryParams() map[string][]string {
qp := map[string][]string{
"descending": {strconv.FormatBool(f.Descending)},
"offset": {strconv.Itoa(f.Offset)},
}
if f.Limit > 0 {
qp["limit"] = []string{strconv.Itoa(f.Limit)}
}
if f.SortBy != "" {
qp["sortBy"] = []string{f.SortBy}
}
return qp
}
// NewPagingLinks returns a PagingLinks.
// num is the number of returned results.
func NewPagingLinks(basePath string, opts FindOptions, f PagingFilter, num int) *PagingLinks {
u := url.URL{
Path: basePath,
}
values := url.Values{}
for k, vs := range f.QueryParams() {
for _, v := range vs {
if v != "" {
values.Add(k, v)
}
}
}
var self, next, prev string
for k, vs := range opts.QueryParams() {
for _, v := range vs {
if v != "" {
values.Add(k, v)
}
}
}
u.RawQuery = values.Encode()
self = u.String()
if num >= opts.Limit {
nextOffset := opts.Offset + opts.Limit
values.Set("offset", strconv.Itoa(nextOffset))
u.RawQuery = values.Encode()
next = u.String()
}
if opts.Offset > 0 {
prevOffset := opts.Offset - opts.Limit
if prevOffset < 0 {
prevOffset = 0
}
values.Set("offset", strconv.Itoa(prevOffset))
u.RawQuery = values.Encode()
prev = u.String()
}
links := &PagingLinks{
Prev: prev,
Self: self,
Next: next,
}
return links
}