forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
paginated_resources.go
45 lines (39 loc) · 1.26 KB
/
paginated_resources.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package ccv3
import (
"encoding/json"
"reflect"
)
// NewPaginatedResources returns a new PaginatedResources struct with the
// given resource type.
func NewPaginatedResources(exampleResource interface{}) *PaginatedResources {
return &PaginatedResources{
resourceType: reflect.TypeOf(exampleResource),
}
}
// PaginatedResources represents a page of resources returned by the Cloud
// Controller.
type PaginatedResources struct {
Pagination struct {
Next struct {
HREF string `json:"href"`
} `json:"next"`
} `json:"pagination"`
ResourcesBytes json.RawMessage `json:"resources"`
resourceType reflect.Type
}
// NextPage returns the HREF of the next page of results.
func (pr PaginatedResources) NextPage() string {
return pr.Pagination.Next.HREF
}
// Resources unmarshals JSON representing a page of resources and returns a
// slice of the given resource type.
func (pr PaginatedResources) Resources() ([]interface{}, error) {
slicePtr := reflect.New(reflect.SliceOf(pr.resourceType))
err := json.Unmarshal([]byte(pr.ResourcesBytes), slicePtr.Interface())
slice := reflect.Indirect(slicePtr)
contents := make([]interface{}, 0, slice.Len())
for i := 0; i < slice.Len(); i++ {
contents = append(contents, slice.Index(i).Interface())
}
return contents, err
}