github.com/prysmaticlabs/prysm@v1.4.4/shared/pagination/pagination.go (about)

     1  // Package pagination contains useful pagination-related helpers.
     2  package pagination
     3  
     4  import (
     5  	"fmt"
     6  	"strconv"
     7  
     8  	"github.com/pkg/errors"
     9  	"github.com/prysmaticlabs/prysm/shared/params"
    10  )
    11  
    12  // StartAndEndPage takes in the requested page token, wanted page size, total page size.
    13  // It returns start, end page and the next page token.
    14  func StartAndEndPage(pageToken string, pageSize, totalSize int) (int, int, string, error) {
    15  	if pageToken == "" {
    16  		pageToken = "0"
    17  	}
    18  	if pageSize == 0 {
    19  		pageSize = params.BeaconConfig().DefaultPageSize
    20  	}
    21  
    22  	token, err := strconv.Atoi(pageToken)
    23  	if err != nil {
    24  		return 0, 0, "", errors.Wrap(err, "could not convert page token")
    25  	}
    26  
    27  	// Start page can not be greater than set size.
    28  	start := token * pageSize
    29  	if start >= totalSize {
    30  		return 0, 0, "", fmt.Errorf("page start %d >= list %d", start, totalSize)
    31  	}
    32  
    33  	// End page can not go out of bound.
    34  	end := start + pageSize
    35  	nextPageToken := strconv.Itoa(token + 1)
    36  
    37  	if end >= totalSize {
    38  		end = totalSize
    39  		nextPageToken = "" // Return an empty next page token for the last page of a set
    40  	}
    41  
    42  	return start, end, nextPageToken, nil
    43  }