forked from andrew-waters/gomo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
paginate.go
45 lines (41 loc) · 1.06 KB
/
paginate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package gomo
import "github.com/moltin/gomo/core"
// NextPage advances the supplied Meta to the next page by returning a new
// offset and limit
func NextPage(meta core.Meta) (int, int) {
offset := meta.Page.Offset + meta.Page.Limit
return offset, meta.Page.Limit
}
// MorePages returns true is the meta suggests there are more results
// available
func MorePages(meta core.Meta) bool {
return meta.Page.Current < meta.Page.Total
}
// Iterate calls the function with a RequestResource that should be
// passed to a Get() request. The function is called for each page
// of size limit. If the function returns an error at any point
// the iteration stops and the error is returned.
func Iterate(limit int, f func(RequestResource) error) error {
meta := core.Meta{
Page: core.MetaPage{
Offset: 0,
Limit: limit,
Current: 0,
Total: 1,
},
}
offset := 0
for MorePages(meta) {
err := f(func(w *wrapper) {
w.apply(
Paginate(offset, limit),
Meta(&meta),
)
})
if err != nil {
return err
}
offset, limit = NextPage(meta)
}
return nil
}