-
Notifications
You must be signed in to change notification settings - Fork 117
/
pagination.go
93 lines (79 loc) · 2.21 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
90
91
92
93
package query
import (
"fmt"
"strconv"
)
const (
// Default pagination limit
DefaultLimit = 1000
lastOffset = int32(1 << 30)
)
// Pagination parses string representation of pagination limit, offset.
// Returns error if limit or offset has invalid syntax or out of range.
func ParsePagination(limit, offset, ptoken, isTotalSizeNeeded string) (*Pagination, error) {
p := new(Pagination)
if limit != "" {
if u, err := strconv.ParseInt(limit, 10, 32); err != nil {
return nil, fmt.Errorf("pagination: limit - %s", err.(*strconv.NumError).Err)
} else if u <= 0 {
return nil, fmt.Errorf("pagination: limit must be a positive value")
} else {
p.Limit = int32(u)
}
}
if offset == "null" {
p.Offset = 0
} else if offset != "" {
if u, err := strconv.ParseInt(offset, 10, 32); err != nil {
return nil, fmt.Errorf("pagination: offset - %s", err.(*strconv.NumError).Err)
} else if u < 0 {
return nil, fmt.Errorf("pagination: offset - negative value")
} else {
p.Offset = int32(u)
}
}
if ptoken != "" {
p.PageToken = ptoken
}
if isTotalSizeNeeded != "" {
u, err := strconv.ParseBool(isTotalSizeNeeded)
if err != nil {
return nil, fmt.Errorf("pagination: is_total_size_needed - %s", err.(*strconv.NumError).Err)
}
p.IsTotalSizeNeeded = u
}
return p, nil
}
// FirstPage returns true if requested first page
func (p *Pagination) FirstPage() bool {
if p.GetPageToken() == "null" || p.GetOffset() == 0 {
return true
}
return false
}
// DefaultLimit returns DefaultLimit if limit was not specified otherwise
// returns either requested or specified one.
func (p *Pagination) DefaultLimit(dl ...int32) int32 {
if l := p.GetLimit(); l != 0 {
return l
}
if len(dl) > 0 && dl[0] > 0 {
return dl[0]
}
return DefaultLimit
}
// SetLastToken sets page info to indicate no more pages are available
func (p *PageInfo) SetLastToken() {
p.PageToken = "null"
}
// SetLastOffset sets page info to indicate no more pages are available
func (p *PageInfo) SetLastOffset() {
p.Offset = lastOffset
}
// NoMore reports whether page info indicates no more pages are available
func (p *PageInfo) NoMore() bool {
if p.GetOffset() == lastOffset || p.GetPageToken() == "null" {
return true
}
return false
}