-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagination.go
67 lines (55 loc) · 1.51 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
package sqld
import "math"
const (
DefaultPageSize = 10
MaxPageSize = 100
)
// ValidatePagination validates and normalizes pagination parameters
func ValidatePagination(req *PaginationRequest) *PaginationRequest {
if req == nil {
return &PaginationRequest{
Page: 1,
PageSize: DefaultPageSize,
}
}
if req.Page < 1 {
req.Page = 1
}
if req.PageSize < 1 {
req.PageSize = DefaultPageSize
}
if req.PageSize > MaxPageSize {
req.PageSize = MaxPageSize
}
return req
}
// CalculateOffset converts page/pageSize into offset
func CalculateOffset(page, pageSize int) int {
return (page - 1) * pageSize
}
// CalculatePagination calculates pagination metadata
func CalculatePagination(totalItems, pageSize, currentPage int) *PaginationResponse {
totalPages := int(math.Ceil(float64(totalItems) / float64(pageSize)))
return &PaginationResponse{
Page: currentPage,
PageSize: pageSize,
TotalItems: totalItems,
TotalPages: totalPages,
}
}
// HasNextPage checks if there is a next page
func HasNextPage(totalItems, pageSize, currentPage int) bool {
return CalculatePagination(totalItems, pageSize, currentPage).TotalPages > currentPage
}
// HasPreviousPage checks if there is a previous page
func HasPreviousPage(currentPage int) bool {
return currentPage > 1
}
// GetNextPage returns the next page number
func GetNextPage(currentPage int) int {
return currentPage + 1
}
// GetPreviousPage returns the previous page number
func GetPreviousPage(currentPage int) int {
return currentPage - 1
}