|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + b64 "encoding/base64" |
| 5 | + |
| 6 | + "github.com/cosmos/cosmos-sdk/client/flags" |
| 7 | + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" |
| 8 | + "github.com/cosmos/cosmos-sdk/types/query" |
| 9 | + "github.com/spf13/pflag" |
| 10 | +) |
| 11 | + |
| 12 | +// ReadPageRequest reads and builds the necessary page request flags for pagination. |
| 13 | +func ReadPageRequest(flagSet *pflag.FlagSet) (*query.PageRequest, error) { |
| 14 | + pageKeyStr, _ := flagSet.GetString(flags.FlagPageKey) |
| 15 | + offset, _ := flagSet.GetUint64(flags.FlagOffset) |
| 16 | + limit, _ := flagSet.GetUint64(flags.FlagLimit) |
| 17 | + countTotal, _ := flagSet.GetBool(flags.FlagCountTotal) |
| 18 | + page, _ := flagSet.GetUint64(flags.FlagPage) |
| 19 | + reverse, _ := flagSet.GetBool(flags.FlagReverse) |
| 20 | + |
| 21 | + if page > 1 && offset > 0 { |
| 22 | + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "page and offset cannot be used together") |
| 23 | + } |
| 24 | + |
| 25 | + // Clear page key if using page numbers (page and key are mutually exclusive) |
| 26 | + if page > 1 { |
| 27 | + offset = (page - 1) * limit |
| 28 | + } |
| 29 | + |
| 30 | + var pageKey []byte |
| 31 | + if pageKeyStr != "" { |
| 32 | + var err error |
| 33 | + pageKey, err = b64.StdEncoding.DecodeString(pageKeyStr) |
| 34 | + if err != nil { |
| 35 | + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "invalid pagination key") |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return &query.PageRequest{ |
| 40 | + Key: pageKey, |
| 41 | + Offset: offset, |
| 42 | + Limit: limit, |
| 43 | + CountTotal: countTotal, |
| 44 | + Reverse: reverse, |
| 45 | + }, nil |
| 46 | +} |
0 commit comments