forked from raystack/guardian
-
Notifications
You must be signed in to change notification settings - Fork 2
/
helper.go
62 lines (52 loc) · 1.29 KB
/
helper.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
package gitlab
import (
"context"
"github.com/goto/guardian/domain"
"github.com/xanzy/go-gitlab"
)
type pageFetcher[T any] func(gitlab.ListOptions, ...gitlab.RequestOptionFunc) ([]T, *gitlab.Response, error)
type mapper[T, T2 any] func(T) T2
func fetchAllPages[T any](
ctx context.Context,
fetchPage pageFetcher[T],
) ([]T, error) {
var records []T
opt := gitlab.ListOptions{
PerPage: 100,
Pagination: "keyset",
OrderBy: "id",
Sort: "asc",
}
options := []gitlab.RequestOptionFunc{gitlab.WithContext(ctx)}
for {
pageRecords, resp, err := fetchPage(opt, options...)
if err != nil {
return nil, err
}
records = append(records, pageRecords...)
if resp.NextLink == "" {
break
}
opt.Page = resp.NextPage
options = []gitlab.RequestOptionFunc{
gitlab.WithContext(ctx),
gitlab.WithKeysetPaginationParameters(resp.NextLink),
}
}
return records, nil
}
func fetchResources[T *gitlab.Group | *gitlab.Project](
ctx context.Context,
fetchFunc pageFetcher[T],
mapFunc mapper[T, *domain.Resource],
) ([]*domain.Resource, error) {
records, err := fetchAllPages(ctx, fetchFunc)
if err != nil {
return nil, err
}
mappedRecords := make([]*domain.Resource, len(records))
for i, r := range records {
mappedRecords[i] = mapFunc(r)
}
return mappedRecords, nil
}