2019-07-02 06:00:46 -07:00
|
|
|
package client
|
|
|
|
|
2020-07-17 08:23:42 -07:00
|
|
|
import (
|
|
|
|
"github.com/cosmos/cosmos-sdk/client/flags"
|
|
|
|
"github.com/cosmos/cosmos-sdk/types/query"
|
|
|
|
"github.com/spf13/pflag"
|
|
|
|
)
|
|
|
|
|
2019-07-02 06:00:46 -07:00
|
|
|
// 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
|
2020-05-13 06:14:43 -07:00
|
|
|
// 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.
|
2019-07-02 06:00:46 -07:00
|
|
|
func Paginate(numObjs, page, limit, defLimit int) (start, end int) {
|
2020-05-13 06:14:43 -07:00
|
|
|
if page <= 0 {
|
2019-07-02 06:00:46 -07:00
|
|
|
// invalid start page
|
|
|
|
return -1, -1
|
2020-05-13 06:14:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// fallback to default limit if supplied limit is invalid
|
|
|
|
if limit <= 0 {
|
|
|
|
if defLimit < 0 {
|
|
|
|
// invalid default limit
|
|
|
|
return -1, -1
|
|
|
|
}
|
2019-07-02 06:00:46 -07:00
|
|
|
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
|
|
|
|
}
|
2020-07-17 08:23:42 -07:00
|
|
|
|
|
|
|
// ReadPageRequest reads and builds the necessary page request flags for pagination.
|
|
|
|
func ReadPageRequest(flagSet *pflag.FlagSet) *query.PageRequest {
|
|
|
|
pageKey, _ := flagSet.GetString(flags.FlagPageKey)
|
|
|
|
offset, _ := flagSet.GetUint64(flags.FlagOffset)
|
|
|
|
limit, _ := flagSet.GetUint64(flags.FlagLimit)
|
|
|
|
countTotal, _ := flagSet.GetBool(flags.FlagCountTotal)
|
|
|
|
|
|
|
|
return &query.PageRequest{
|
|
|
|
Key: []byte(pageKey),
|
|
|
|
Offset: offset,
|
|
|
|
Limit: limit,
|
|
|
|
CountTotal: countTotal,
|
|
|
|
}
|
|
|
|
}
|