github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+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 struct {
    20  		Next struct {
    21  			HREF string `json:"href"`
    22  		} `json:"next"`
    23  	} `json:"pagination"`
    24  	ResourcesBytes json.RawMessage `json:"resources"`
    25  	resourceType   reflect.Type
    26  }
    27  
    28  // NextPage returns the HREF of the next page of results.
    29  func (pr PaginatedResources) NextPage() string {
    30  	return pr.Pagination.Next.HREF
    31  }
    32  
    33  // Resources unmarshals JSON representing a page of resources and returns a
    34  // slice of the given resource type.
    35  func (pr PaginatedResources) Resources() ([]interface{}, error) {
    36  	slicePtr := reflect.New(reflect.SliceOf(pr.resourceType))
    37  	err := json.Unmarshal([]byte(pr.ResourcesBytes), slicePtr.Interface())
    38  	slice := reflect.Indirect(slicePtr)
    39  
    40  	contents := make([]interface{}, 0, slice.Len())
    41  	for i := 0; i < slice.Len(); i++ {
    42  		contents = append(contents, slice.Index(i).Interface())
    43  	}
    44  	return contents, err
    45  }