-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopaginate.go
82 lines (70 loc) · 2.15 KB
/
gopaginate.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
package gopaginate
import (
"context"
"errors"
"github.com/jackc/pgx/v5/pgxpool"
"net/http"
"regexp"
"strconv"
)
func New(db *pgxpool.Pool, sql string, r *http.Request) (int16, int16, int16, int16, int16, int16, int16, error) {
pageParam := r.URL.Query().Get("page")
limitParam := r.URL.Query().Get("limit")
cleanPage := regexp.MustCompile("[^0-9]+")
cleanLimit := regexp.MustCompile("[^0-9]+")
finalPageParam := cleanPage.ReplaceAllString(pageParam, "")
finalLimitParam := cleanLimit.ReplaceAllString(limitParam, "")
var errPagination error
if finalPageParam == "" || finalPageParam == "0" {
finalPageParam = "1"
}
if finalLimitParam == "" || finalLimitParam == "0" {
finalLimitParam = "10"
}
currentPage, errParsePage := strconv.ParseInt(finalPageParam, 10, 64)
if errParsePage != nil {
errPagination = errors.New("error parse page")
}
limit, errParseLimit := strconv.ParseInt(finalLimitParam, 10, 64)
if errParseLimit != nil {
errPagination = errors.New("error parse limit")
}
offSet := (currentPage - 1) * limit
totalCount, errCount := getTotalUsersCount(r.Context(), db, sql)
if errCount != nil {
errPagination = errors.New("error parse counting page")
}
totalPages := calculateTotalPages(totalCount, int16(limit))
nextPage := currentPage + 1
prevPage := currentPage - 1
isNextPage := getNextPage(totalPages, int16(nextPage))
isPrevPage := getPrevPage(int16(prevPage))
totalData := totalCount
finalCurrentPage := int16(currentPage)
finalLimit := int16(limit)
finalOffset := int16(offSet)
return finalCurrentPage, finalLimit, finalOffset, totalPages, isNextPage, isPrevPage, totalData, errPagination
}
func getTotalUsersCount(ctx context.Context, db *pgxpool.Pool, sql string) (int16, error) {
var count int16
errCount := db.QueryRow(ctx, sql).Scan(&count)
return count, errCount
}
func calculateTotalPages(totalCount, limit int16) int16 {
if totalCount/limit == 0 {
return totalCount / limit
}
return totalCount/limit + 1
}
func getNextPage(totalPages, nextPage int16) int16 {
if nextPage <= totalPages {
return nextPage
}
return -1
}
func getPrevPage(prevPage int16) int16 {
if prevPage > 0 {
return prevPage
}
return -1
}