github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/client/utils.go (about)

     1  package client
     2  
     3  import (
     4  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/client/flags"
     5  	sdkerrors "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types/errors"
     6  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types/query"
     7  	"github.com/spf13/pflag"
     8  )
     9  
    10  // Paginate returns the correct starting and ending index for a paginated query,
    11  // given that client provides a desired page and limit of objects and the handler
    12  // provides the total number of objects. If the start page is invalid, non-positive
    13  // values are returned signaling the request is invalid.
    14  //
    15  // NOTE: The start page is assumed to be 1-indexed.
    16  func Paginate(numObjs, page, limit, defLimit int) (start, end int) {
    17  	if page == 0 {
    18  		// invalid start page
    19  		return -1, -1
    20  	} else if limit == 0 {
    21  		limit = defLimit
    22  	}
    23  
    24  	start = (page - 1) * limit
    25  	end = limit + start
    26  
    27  	if end >= numObjs {
    28  		end = numObjs
    29  	}
    30  
    31  	if start >= numObjs {
    32  		// page is out of bounds
    33  		return -1, -1
    34  	}
    35  
    36  	return start, end
    37  }
    38  
    39  // ReadPageRequest reads and builds the necessary page request flags for pagination.
    40  func ReadPageRequest(flagSet *pflag.FlagSet) (*query.PageRequest, error) {
    41  	pageKey, _ := flagSet.GetString(flags.FlagPageKey)
    42  	offset, _ := flagSet.GetUint64(flags.FlagOffset)
    43  	limit, _ := flagSet.GetUint64(flags.FlagLimit)
    44  	countTotal, _ := flagSet.GetBool(flags.FlagCountTotal)
    45  	page, _ := flagSet.GetUint64(flags.FlagPage)
    46  
    47  	if page > 1 && offset > 0 {
    48  		return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "page and offset cannot be used together")
    49  	}
    50  
    51  	if page > 1 {
    52  		offset = (page - 1) * limit
    53  	}
    54  
    55  	return &query.PageRequest{
    56  		Key:        []byte(pageKey),
    57  		Offset:     offset,
    58  		Limit:      limit,
    59  		CountTotal: countTotal,
    60  	}, nil
    61  }