github.com/wanddynosios/cli/v8@v8.7.9-0.20240221182337-1a92e3a7017f/api/cloudcontroller/ccv3/paginated_resources.go (about)

     1  package ccv3
     2  
     3  import (
     4  	"encoding/json"
     5  	"reflect"
     6  )
     7  
     8  // NewPaginatedResources returns a new PaginatedResources struct with the
     9  // given resource type.
    10  func NewPaginatedResources(exampleResource interface{}) *PaginatedResources {
    11  	return &PaginatedResources{
    12  		resourceType: reflect.TypeOf(exampleResource),
    13  	}
    14  }
    15  
    16  // PaginatedResources represents a page of resources returned by the Cloud
    17  // Controller.
    18  type PaginatedResources struct {
    19  	// Pagination represents information about the paginated resource.
    20  	Pagination struct {
    21  		// Next represents a link to the next page.
    22  		Next struct {
    23  			// HREF is the HREF of the next page.
    24  			HREF string `json:"href"`
    25  		} `json:"next"`
    26  	} `json:"pagination"`
    27  	// ResourceBytes is the list of resources for the current page.
    28  	ResourcesBytes    json.RawMessage `json:"resources"`
    29  	resourceType      reflect.Type
    30  	IncludedResources IncludedResources `json:"included"`
    31  }
    32  
    33  // NextPage returns the HREF of the next page of results.
    34  func (pr PaginatedResources) NextPage() string {
    35  	return pr.Pagination.Next.HREF
    36  }
    37  
    38  // Resources unmarshals JSON representing a page of resources and returns a
    39  // slice of the given resource type.
    40  func (pr PaginatedResources) Resources() ([]interface{}, error) {
    41  	slicePtr := reflect.New(reflect.SliceOf(pr.resourceType))
    42  	err := json.Unmarshal([]byte(pr.ResourcesBytes), slicePtr.Interface())
    43  	slice := reflect.Indirect(slicePtr)
    44  
    45  	contents := make([]interface{}, 0, slice.Len())
    46  	for i := 0; i < slice.Len(); i++ {
    47  		contents = append(contents, slice.Index(i).Interface())
    48  	}
    49  	return contents, err
    50  }