forked from gobeam/mongo-go-pagination
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpagination.go
91 lines (83 loc) · 2.1 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
package mongopagination
import (
"context"
"math"
)
// Paginator struct for holding pagination info
type Paginator struct {
TotalRecord int `json:"total_record"`
TotalPage int `json:"total_page"`
Offset int `json:"offset"`
Limit int `json:"limit"`
Page int `json:"page"`
PrevPage int `json:"prev_page"`
NextPage int `json:"next_page"`
}
// PaginationData struct for returning pagination stat
type PaginationData struct {
Total int `json:"total"`
Page int `json:"page"`
PerPage int `json:"perPage"`
Prev int `json:"prev"`
Next int `json:"next"`
TotalPages int `json:"totalPages"`
RecordsOnPage int `json:"recordsOnPage"`
}
// PaginationData returns PaginationData struct which
// holds information of all stats needed for pagination
func (p *Paginator) PaginationData() *PaginationData {
data := PaginationData{
Total: p.TotalRecord,
Page: p.Page,
PerPage: p.Limit,
Prev: 0,
Next: 0,
TotalPages: p.TotalPage,
}
if p.Page != p.PrevPage && p.TotalRecord > 0 {
data.Prev = p.PrevPage
}
if p.Page != p.NextPage && p.TotalRecord > 0 && p.Page <= p.TotalPage {
data.Next = p.NextPage
}
return &data
}
// Paging returns Paginator struct which hold pagination
// stats
func Paging(p *PagingQuery) *Paginator {
if p.Page < 1 {
p.Page = 1
}
if p.Limit == 0 {
p.Limit = 10
}
var paginator Paginator
var offset int
var total int64
if len(p.Filter) == 0 {
total, _ = p.Collection.EstimatedDocumentCount(context.Background())
} else {
total, _ = p.Collection.CountDocuments(context.Background(), p.Filter)
}
if p.Page == 1 {
offset = 0
} else {
offset = (p.Page - 1) * p.Limit
}
paginator.TotalRecord = int(total)
paginator.Page = p.Page
paginator.Offset = offset
paginator.Limit = p.Limit
paginator.TotalPage = int(math.Ceil(float64(total) / float64(p.Limit)))
if p.Page > 1 {
paginator.PrevPage = p.Page - 1
} else {
paginator.PrevPage = p.Page
}
if p.Page == paginator.TotalPage {
paginator.NextPage = p.Page
} else {
paginator.NextPage = p.Page + 1
}
return &paginator
}