Skip to content

Include more modern example of handling pagination #861

@nicois

Description

@nicois

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
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions