godo icon indicating copy to clipboard operation
godo copied to clipboard

Include more modern example of handling pagination

Open nicois opened this issue 6 months ago • 1 comments

Consider the inclusion of something like the following in the package's README, as an alternative to the existing recommended boilerplate for handling paginated responses.

Generics were introduced in version 1.18, and the iter.Seq function in 1.23. Many existing and potential users of godo would benefit from an example utlising these packages:

func Unpaginate[T any](ctx context.Context, f func(ctx context.Context, opt *godo.ListOptions) ([]T, *godo.Response, error), opt godo.ListOptions) iter.Seq2[T, error] {
	return func(yield func(T, error) bool) {
		var buffer T
		for {
			items, resp, err := f(ctx, &opt)
			if err != nil {
				yield(buffer, err)
				return
			}
			for _, item := range items {
				if !yield(item, nil) {
					return
				}
			}
			if resp.Links == nil || resp.Links.IsLastPage() {
				return
			}

			page, err := resp.Links.CurrentPage()
			if err != nil {
				yield(buffer, err)
				return
			}

			// set the page we want for the next request
			opt.Page = page + 1
		}
	}
}

nicois avatar Jul 01 '25 07:07 nicois

Hi i would like to work on this issue . Please assign it to me @nicois @chuyeow

ProgrammingPirates avatar Oct 08 '25 08:10 ProgrammingPirates