-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add generic paginator * improve NextPage * improve NextPage
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
} |