forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutils.go
69 lines (57 loc) · 1.8 KB
/
utils.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
package client
import (
"github.com/spf13/pflag"
"github.com/cosmos/cosmos-sdk/client/flags"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/query"
)
// Paginate returns the correct starting and ending index for a paginated query,
// given that client provides a desired page and limit of objects and the handler
// provides the total number of objects. The start page is assumed to be 1-indexed.
// If the start page is invalid, non-positive values are returned signaling the
// request is invalid; it returns non-positive values if limit is non-positive and
// defLimit is negative.
func Paginate(numObjs, page, limit, defLimit int) (start, end int) {
if page <= 0 {
// invalid start page
return -1, -1
}
// fallback to default limit if supplied limit is invalid
if limit <= 0 {
if defLimit < 0 {
// invalid default limit
return -1, -1
}
limit = defLimit
}
start = (page - 1) * limit
end = limit + start
if end >= numObjs {
end = numObjs
}
if start >= numObjs {
// page is out of bounds
return -1, -1
}
return start, end
}
// ReadPageRequest reads and builds the necessary page request flags for pagination.
func ReadPageRequest(flagSet *pflag.FlagSet) (*query.PageRequest, error) {
pageKey, _ := flagSet.GetString(flags.FlagPageKey)
offset, _ := flagSet.GetUint64(flags.FlagOffset)
limit, _ := flagSet.GetUint64(flags.FlagLimit)
countTotal, _ := flagSet.GetBool(flags.FlagCountTotal)
page, _ := flagSet.GetUint64(flags.FlagPage)
if page > 1 && offset > 0 {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "page and offset cannot be used together")
}
if page > 1 {
offset = (page - 1) * limit
}
return &query.PageRequest{
Key: []byte(pageKey),
Offset: offset,
Limit: limit,
CountTotal: countTotal,
}, nil
}