Skip to content

Commit

Permalink
feat: add experimental iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
costela committed Feb 14, 2024
1 parent 9067982 commit fb83965
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 8 deletions.
41 changes: 41 additions & 0 deletions iterator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//go:build go1.22 && goexperiment.rangefunc
// +build go1.22,goexperiment.rangefunc

package gitlab

import (
"iter"
)

// PageIterator is an EXPERIMENTAL iterator as defined in the "rangefunc" experiment for go 1.22.
// See https://go.dev/wiki/RangefuncExperiment for more details.
//
// It can be used as:
//
// for user, err := range gitlab.PageIterator(gl.Users.List, nil) {
// if err != nil {
// // handle error
// }
// // process individual user
// }
func PageIterator[O, T any](f Paginatable[O, T], opt *O, optFunc ...RequestOptionFunc) iter.Seq2[*T, error] {
return func(yield func(*T, error) bool) {
nextLink := ""
for {
page, resp, err := f(opt, append(optFunc, WithKeysetPaginationParameters(nextLink))...)
if err != nil {
yield(nil, err)
return
}
for _, p := range page {
if !yield(p, nil) {
return
}
}
if resp.NextLink == "" {
break
}
nextLink = resp.NextLink
}
}
}
20 changes: 12 additions & 8 deletions pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,22 @@ package gitlab
//
// It is also possible to specify additional pagination parameters:
//
// mrs, err := gitlab.AllPages(gl.MergeRequests.ListMergeRequests, &gitlab.ListMergeRequestsOptions{
// ListOptions: gitlab.ListOptions{
// PerPage: 100,
// Pagination: "keyset",
// OrderBy: "created_at",
// mrs, err := gitlab.AllPages(
// gl.MergeRequests.ListMergeRequests,
// &gitlab.ListMergeRequestsOptions{
// ListOptions: gitlab.ListOptions{
// PerPage: 100,
// Pagination: "keyset",
// OrderBy: "created_at",
// },
// },
// })
func AllPages[O, T any](f Paginatable[O, T], opt *O) ([]*T, error) {
// gitlab.WithContext(ctx),
// )
func AllPages[O, T any](f Paginatable[O, T], opt *O, optFunc ...RequestOptionFunc) ([]*T, error) {
all := make([]*T, 0)
nextLink := ""
for {
page, resp, err := f(opt, WithKeysetPaginationParameters(nextLink))
page, resp, err := f(opt, append(optFunc, WithKeysetPaginationParameters(nextLink))...)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit fb83965

Please sign in to comment.