github.com/franc20/ayesa_sap@v7.0.0-beta.28.0.20200124003224-302d4d52fa6c+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  	IncludedResources struct {
    31  		UserResource []User `json:"users"`
    32  	} `json:"included"`
    33  }
    34  
    35  // NextPage returns the HREF of the next page of results.
    36  func (pr PaginatedResources) NextPage() string {
    37  	return pr.Pagination.Next.HREF
    38  }
    39  
    40  // Resources unmarshals JSON representing a page of resources and returns a
    41  // slice of the given resource type.
    42  func (pr PaginatedResources) Resources() ([]interface{}, error) {
    43  	slicePtr := reflect.New(reflect.SliceOf(pr.resourceType))
    44  	err := json.Unmarshal([]byte(pr.ResourcesBytes), slicePtr.Interface())
    45  	slice := reflect.Indirect(slicePtr)
    46  
    47  	contents := make([]interface{}, 0, slice.Len())
    48  	for i := 0; i < slice.Len(); i++ {
    49  		contents = append(contents, slice.Index(i).Interface())
    50  	}
    51  	return contents, err
    52  }