github.com/chnsz/golangsdk@v0.0.0-20240506093406-85a3fbfa605b/pagination/pagesize.go (about)

     1  package pagination
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"strings"
     7  
     8  	"github.com/chnsz/golangsdk"
     9  )
    10  
    11  // PageSizeBase is used for paging queries based on "page" and "pageSize".
    12  // You can change the parameter name of the current page number by overriding the GetPageName method.
    13  type PageSizeBase struct {
    14  	PageResult
    15  }
    16  
    17  // GetPageName Overwrite this function for changing the parameter name of the current page number
    18  // Default value is "page"
    19  func (current PageSizeBase) GetPageName() string {
    20  	return "page"
    21  }
    22  
    23  // NextPageURL generates the URL for the page of results after this one.
    24  func (current PageSizeBase) NextPageURL() (string, error) {
    25  	currentURL := current.URL
    26  
    27  	q := currentURL.Query()
    28  	pageNum := q.Get(current.GetPageName())
    29  	if pageNum == "" {
    30  		pageNum = "1"
    31  	}
    32  
    33  	sizeVal, err := strconv.ParseInt(pageNum, 10, 32)
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  
    38  	pageNum = strconv.Itoa(int(sizeVal + 1))
    39  	q.Set(current.GetPageName(), pageNum)
    40  	currentURL.RawQuery = q.Encode()
    41  	return currentURL.String(), nil
    42  }
    43  
    44  // IsEmpty satisifies the IsEmpty method of the Page interface
    45  func (current PageSizeBase) IsEmpty() (bool, error) {
    46  	if pb, ok := current.Body.(map[string]interface{}); ok {
    47  		for k, v := range pb {
    48  			// ignore xxx_links
    49  			if !strings.HasSuffix(k, "links") {
    50  				// check the field's type. we only want []interface{} (which is really []map[string]interface{})
    51  				switch vt := v.(type) {
    52  				case []interface{}:
    53  					return len(vt) == 0, nil
    54  				}
    55  			}
    56  		}
    57  	}
    58  	if pb, ok := current.Body.([]interface{}); ok {
    59  		return len(pb) == 0, nil
    60  	}
    61  
    62  	err := golangsdk.ErrUnexpectedType{}
    63  	err.Expected = "map[string]interface{}/[]interface{}"
    64  	err.Actual = fmt.Sprintf("%T", current.Body)
    65  	return true, err
    66  }
    67  
    68  // GetBody returns the linked page's body. This method is needed to satisfy the
    69  // Page interface.
    70  func (current PageSizeBase) GetBody() interface{} {
    71  	return current.Body
    72  }