-
Notifications
You must be signed in to change notification settings - Fork 10
/
pagination.go
92 lines (75 loc) · 2.29 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package artifact
import (
"github.com/pilagod/gorm-cursor-paginator/v2/paginator"
"gorm.io/gorm"
"math"
"strconv"
)
var Pagination paginator.Paginator
type PaginationMeta struct {
CurrentPage int `json:"current_page"`
PerPage int `json:"per_page"`
LastPage int `json:"last_page"`
Total int64 `json:"total"`
}
type Paginator struct {
Meta PaginationMeta `json:"meta"`
db *gorm.DB
*paginator.Paginator
model interface{}
filter map[string]interface{}
}
func (paginator *Paginator) PaginateScope(page int, limit int) func(db *gorm.DB) *gorm.DB {
if page == 0 {
page = 1
}
if limit == 0 {
limit = 10
}
var totalRows int64
paginator.Meta.CurrentPage = page
paginator.Meta.PerPage = limit
DB.Model(paginator.model).Where(paginator.filter).Count(&totalRows)
paginator.Meta.Total = totalRows
paginator.Meta.LastPage = int(math.Ceil(float64(totalRows) / float64(limit)))
return func(db *gorm.DB) *gorm.DB {
offset := (paginator.Meta.CurrentPage - 1) * paginator.Meta.PerPage
return db.Offset(offset).Limit(paginator.Meta.PerPage)
}
}
func (paginator *Paginator) CursorPaginate(query *gorm.DB, v interface{}) (*gorm.DB, paginator.Cursor, error) {
return paginator.Paginate(query, v)
}
func (paginator *Paginator) updateMeta(v interface{}, request map[string]interface{}) {
limit, _ := strconv.ParseInt(request["limit"].(string), 10, 64)
page, _ := strconv.ParseInt(request["page"].(string), 10, 64)
if request["after"] != nil && request["after"] != "" {
paginator.SetAfterCursor(request["after"].(string))
}
if request["before"] != nil && request["before"] != "" {
paginator.SetBeforeCursor(request["before"].(string))
}
if limit == 0 {
limit = 10
}
if page == 0 {
page = 1
}
paginator.SetLimit(int(limit))
paginator.Meta.CurrentPage = int(page)
paginator.Meta.PerPage = int(limit)
var totalRows int64
DB.Model(v).Count(&totalRows)
paginator.Meta.Total = totalRows
paginator.Meta.LastPage = int(math.Ceil(float64(totalRows) / float64(limit)))
}
func NewPaginator(v interface{}, queryFilter map[string]interface{}) *Paginator {
opts := []paginator.Option{
&paginator.Config{
Order: paginator.ASC,
},
}
p := paginator.New(opts...)
newInstance := &Paginator{Meta: PaginationMeta{}, Paginator: p, model: v, filter: queryFilter}
return newInstance
}