-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagination.go
68 lines (54 loc) · 1.17 KB
/
pagination.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package pagination
import "gorm.io/gorm"
type Paginator struct {
Page int `json:"page"`
Limit int `json:"limit"`
Total int64 `json:"total"`
Data interface{} `json:"data"`
}
type Option struct {
DB *gorm.DB
Page int
Limit int
ShowSQL bool
}
func Paginate(o *Option, data interface{}) *Paginator {
db := o.DB
if o.ShowSQL {
db = db.Debug()
}
o.Page, o.Limit = defaultPageInfo(o.Page, o.Limit)
paginator := &Paginator{
Page: o.Page,
Limit: o.Limit,
}
done := make(chan bool, 1)
go count(db, data, &paginator.Total, done)
db.Scopes(Page(o.Page, o.Limit)).Find(data)
paginator.Data = data
<-done
return paginator
}
func Page(page, limit int) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
page, limit = defaultPageInfo(page, limit)
offset := (page - 1) * limit
return db.Offset(offset).Limit(limit)
}
}
func count(db *gorm.DB, model interface{}, total *int64, done chan bool) {
db.Model(model).Count(total)
done <- true
}
func defaultPageInfo(page, limit int) (int, int) {
if page < 1 {
page = 1
}
switch {
case limit > 100:
limit = 100
case limit < 1:
limit = 10
}
return page, limit
}