Skip to content
This repository has been archived by the owner on Dec 2, 2022. It is now read-only.

Commit

Permalink
feat: add foreach util function
Browse files Browse the repository at this point in the history
Signed-off-by: nscuro <[email protected]>
  • Loading branch information
nscuro committed Oct 17, 2022
1 parent de4afb5 commit a24e5e3
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions util.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,45 @@
package dtrack

import "fmt"

// FetchAll is a convenience function to retrieve all items of a paginated API resource.
func FetchAll[T any](f func(po PageOptions) (Page[T], error)) (items []T, err error) {
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 = f(PageOptions{
page, err = pageFetchFunc(PageOptions{
PageNumber: pageNumber,
PageSize: pageSize,
})
if err != nil {
break
}

items = append(items, page.Items...)
if len(page.Items) == 0 || len(items) >= page.TotalCount {
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 += page.TotalCount
if len(page.Items) == 0 || itemsSeen >= page.TotalCount {
break
}

Expand Down

0 comments on commit a24e5e3

Please sign in to comment.