github.com/arunkumar7540/cli@v6.45.0+incompatible/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  }
    31  
    32  // NextPage returns the HREF of the next page of results.
    33  func (pr PaginatedResources) NextPage() string {
    34  	return pr.Pagination.Next.HREF
    35  }
    36  
    37  // Resources unmarshals JSON representing a page of resources and returns a
    38  // slice of the given resource type.
    39  func (pr PaginatedResources) Resources() ([]interface{}, error) {
    40  	slicePtr := reflect.New(reflect.SliceOf(pr.resourceType))
    41  	err := json.Unmarshal([]byte(pr.ResourcesBytes), slicePtr.Interface())
    42  	slice := reflect.Indirect(slicePtr)
    43  
    44  	contents := make([]interface{}, 0, slice.Len())
    45  	for i := 0; i < slice.Len(); i++ {
    46  		contents = append(contents, slice.Index(i).Interface())
    47  	}
    48  	return contents, err
    49  }