-
Notifications
You must be signed in to change notification settings - Fork 2
/
collection.go
215 lines (177 loc) · 5.28 KB
/
collection.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package paddle
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/url"
"sync"
"github.com/PaddleHQ/paddle-go-sdk/v3/internal/client"
"github.com/PaddleHQ/paddle-go-sdk/v3/internal/response"
)
// Collection is the response from a listing endpoint in the Paddle API.
// It is used as a container to iterate over many pages of results.
type Collection[T any] struct {
client Doer
m sync.RWMutex
pos uint32
results []*Res[T]
nextURL *url.URL
itemsPerPage int
estimatedTotal int
hasMore bool
}
// PerPage returns the number of items per page in the collection.
func (c *Collection[T]) PerPage() int {
return c.itemsPerPage
}
// EstimatedTotal returns the estimated number of items in the collection.
func (c *Collection[T]) EstimatedTotal() int {
return c.estimatedTotal
}
// HasMore returns true if there are more pages of results to be fetched.
func (c *Collection[T]) HasMore() bool {
return c.hasMore
}
// Res is a single result returned from an iteration of a collection.
type Res[T any] struct {
value T
err error
end bool
}
// Ok returns true if the result is not an error and not the end of the
// collection.
func (r *Res[T]) Ok() bool {
return !r.end
}
// Err returns the error from the result, if it exists. This should be checked
// on each iteration.
func (r *Res[T]) Err() error {
return r.err
}
// Value returns the value contained from the result.
func (r *Res[T]) Value() T {
return r.value
}
// Next returns the next result from the collection.
// If there are no more results, the result will response to Ok() with false.
func (c *Collection[T]) Next(ctx context.Context) *Res[T] {
// We need to lock, as we mutate the underlying position and read values in
// sequence. It is unlikely that multiple consumers will be reading from the
// same collection as it provides no real performance benefit, however this
// prevents a possible data-race with misuse.
c.m.Lock()
defer c.m.Unlock()
// If we're about to seek past the end of the results, we need to fetch the
// next page of results.
if c.pos >= uint32(len(c.results)) {
if !c.hasMore {
return &Res[T]{end: true}
}
err := c.client.Do(ctx, http.MethodGet, c.nextURL.String(), nil, &c)
if err != nil {
return &Res[T]{end: true, err: err}
}
if len(c.results) == 0 {
return &Res[T]{end: true}
}
}
// Copy the result, as the next iteration may reset results.
ptrCopy := *c.results[c.pos]
c.pos++
return &ptrCopy
}
// Ensure that Collection[T] implements the response.Unmarshaler and the
// client.Wanter interfaces.
var (
_ response.UnmarshalsResponses = &Collection[any]{}
_ json.Unmarshaler = &Collection[any]{}
_ client.Wanter = &Collection[any]{}
)
// Wants sets the client to be used for making requests.
func (c *Collection[T]) Wants(d client.Doer) {
c.client = d
}
// Iter iterates over the collection, calling the given function for each result.
// If the function returns false, the iteration will stop.
// You should check the error given to your callback function on each iteration.
func (c *Collection[T]) Iter(ctx context.Context, fn func(v T) (bool, error)) error {
for {
r := c.Next(ctx)
if !r.Ok() {
return r.Err()
}
cont, err := fn(r.Value())
if err != nil {
return err
}
if !cont {
return nil
}
}
}
// ErrStopIteration is used as a return from the iteration function to stop the
// iteration from proceeding. It will ensure that IterErr returns nil.
var ErrStopIteration = errors.New("stop iteration")
// IterErr iterates over the collection, calling the given function for each
// result.
// If the function returns false, the iteration will stop.
// You should check the error given to the function on each iteration.
func (c *Collection[T]) IterErr(ctx context.Context, fn func(v T) error) error {
for {
r := c.Next(ctx)
if !r.Ok() {
return r.Err()
}
err := fn(r.Value())
if err != nil && errors.Is(err, ErrStopIteration) {
return nil
} else if err != nil {
return err
}
}
}
// UnmarshalsResponses acts as a marker to identify this struct must Unmarshal the entire response.
func (c *Collection[T]) UnmarshalsResponses() {}
// UnmarshalJSON unmarshals the collection from a JSON response.
func (c *Collection[T]) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return nil
}
// Unmarshal into an intermediary struct with delayed decoding
var res response.Response[[]json.RawMessage]
if err := json.Unmarshal(b, &res); err != nil {
return err
}
// Reset results.
c.results = nil
c.pos = 0
for _, item := range res.Data {
switch any(c).(type) {
case *Collection[Event]:
e, err := unmarshalEvent(item)
if err != nil {
return err
}
c.results = append(c.results, &Res[T]{value: any(e).(T)}) //nolint:forcetypeassert // we know the type is correct.
default:
var t T
if err := json.Unmarshal(item, &t); err != nil {
return err
}
c.results = append(c.results, &Res[T]{value: t}) //nolint:forcetypeassert // we know the type is correct.
}
}
if res.Meta.Pagination == nil {
return nil
}
nextURL, err := url.Parse(res.Meta.Pagination.Next)
if err != nil {
return err
}
c.itemsPerPage = res.Meta.Pagination.PerPage
c.nextURL = nextURL
c.estimatedTotal = res.Meta.Pagination.EstimatedTotal
c.hasMore = res.Meta.Pagination.HasMore
return nil
}