From 90679829c80bfd39d5a8ae1ae5c3a9443a93aeca Mon Sep 17 00:00:00 2001 From: Leo Antunes Date: Mon, 5 Feb 2024 22:31:46 +0100 Subject: [PATCH] feat: add AllPages pagination helper --- pagination.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 pagination.go diff --git a/pagination.go b/pagination.go new file mode 100644 index 000000000..0bfb0f561 --- /dev/null +++ b/pagination.go @@ -0,0 +1,34 @@ +package gitlab + +// AllPages can be used to fetch all pages of a paginated resource, e.g.: (assuming gl is a gitlab client instance) +// +// allUsers, err := gitlab.AllPages(gl.Users.List, nil) +// +// 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", +// }, +// }) +func AllPages[O, T any](f Paginatable[O, T], opt *O) ([]*T, error) { + all := make([]*T, 0) + nextLink := "" + for { + page, resp, err := f(opt, WithKeysetPaginationParameters(nextLink)) + if err != nil { + return nil, err + } + all = append(all, page...) + if resp.NextLink == "" { + break + } + nextLink = resp.NextLink + } + return all, nil +} + +// Paginatable is the type that is implemented by all functions used to paginated content. +type Paginatable[O, T any] func(*O, ...RequestOptionFunc) ([]*T, *Response, error)