forked from simplesurance/bunny-go
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_list.go
71 lines (60 loc) · 1.93 KB
/
resource_list.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package bunny
import "context"
const (
// DefaultPaginationPage is the default value that is used for
// PaginationOptions.Page if it is unset.
DefaultPaginationPage = 1
// DefaultPaginationPerPage is the default value that is used for
// PaginationOptions.PerPage if it is unset.
DefaultPaginationPerPage = 1000
)
// PaginationOptions specifies optional parameters for List APIs.
type PaginationOptions struct {
// Page the page to return
Page int32 `url:"page,omitempty"`
// PerPage how many entries to return per page
PerPage int32 `url:"per_page,omitempty"`
}
// PaginationReply represents the pagination information contained in a
// List API endpoint response.
//
// Ex. Bunny.net API docs:
// - https://docs.bunny.net/reference/pullzonepublic_index
// - https://docs.bunny.net/reference/storagezonepublic_index
type PaginationReply[Item any] struct {
Items []*Item `json:"Items,omitempty"`
CurrentPage *int32 `json:"CurrentPage"`
TotalItems *int32 `json:"TotalItems"`
HasMoreItems *bool `json:"HasMoreItems"`
}
func (p *PaginationOptions) ensureConstraints() {
if p.Page < 1 {
p.Page = DefaultPaginationPage
}
if p.PerPage < 1 {
p.PerPage = DefaultPaginationPerPage
}
}
func resourceList[Resp any](ctx context.Context, client *Client, path string, opts *PaginationOptions) (*Resp, error) {
// Ensure that opts.Page is >=1, if it isn't bunny.net will send a
// different response JSON object, that contains only a single Object,
// without items and paginations fields. Enforcing opts.page =>1 ensures
// that we always unmarshall into the same struct.
if opts == nil {
opts = &PaginationOptions{
Page: DefaultPaginationPage,
PerPage: DefaultPaginationPerPage,
}
} else {
opts.ensureConstraints()
}
req, err := client.newGetRequest(path, opts)
if err != nil {
return nil, err
}
var res Resp
if err := client.sendRequest(ctx, req, &res); err != nil {
return nil, err
}
return &res, nil
}