forked from DependencyTrack/client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
50 lines (40 loc) · 1.06 KB
/
util.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
package dtrack
import "fmt"
// FetchAll is a convenience function to retrieve all items of a paginated API resource.
func FetchAll[T any](pageFetchFunc func(po PageOptions) (Page[T], error)) (items []T, err error) {
err = ForEach(pageFetchFunc, func(item T) error {
items = append(items, item)
return nil
})
return
}
// ForEach is a convenience function to perform an action on every item of a paginated API resource.
func ForEach[T any](pageFetchFunc func(po PageOptions) (Page[T], error), handlerFunc func(item T) error) (err error) {
const pageSize = 50
var (
page Page[T]
pageNumber = 1
itemsSeen = 0
)
for {
page, err = pageFetchFunc(PageOptions{
PageNumber: pageNumber,
PageSize: pageSize,
})
if err != nil {
break
}
for i := range page.Items {
err = handlerFunc(page.Items[i])
if err != nil {
return fmt.Errorf("failed to handle item %d on page %d: %w", i+1, pageNumber, err)
}
}
itemsSeen += len(page.Items)
if len(page.Items) == 0 || itemsSeen >= page.TotalCount {
break
}
pageNumber++
}
return
}