From fd7c1ec05547ff308a3d4c1e7e9cd2e0efaa283a Mon Sep 17 00:00:00 2001 From: Lukasz Zajaczkowski Date: Tue, 12 Mar 2024 16:58:11 +0100 Subject: [PATCH] add generic paginator (#24) * add generic paginator * improve NextPage * improve NextPage --- algorithms/pager.go | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 algorithms/pager.go diff --git a/algorithms/pager.go b/algorithms/pager.go new file mode 100644 index 0000000..c7d29d9 --- /dev/null +++ b/algorithms/pager.go @@ -0,0 +1,50 @@ +package algorithms + +type FetchPageFunc[T any] func(page *string, size int64) ([]T, *PageInfo, error) + +type PageInfo struct { + HasNext bool + After *string + PageSize int64 +} + +type Pager[T any] struct { + pageInfo *PageInfo + err error + + fetchPage FetchPageFunc[T] +} + +type PageIter[T any] interface { + NextPage() ([]T, error) +} + +func NewPager[T any](pageSize int64, fetchPage FetchPageFunc[T]) *Pager[T] { + p := &Pager[T]{ + fetchPage: fetchPage, + } + p.pageInfo = &PageInfo{ + HasNext: true, + After: nil, + PageSize: pageSize, + } + return p +} + +func (p *Pager[T]) NextPage() ([]T, error) { + var list []T + + if !p.pageInfo.HasNext { + return nil, nil + } + + list, p.pageInfo, p.err = p.fetchPage(p.pageInfo.After, p.pageInfo.PageSize) + if p.err != nil { + return nil, p.err + } + return list, nil +} + +func (p *Pager[T]) HasNext() bool { + return p.pageInfo.HasNext +}