aboutsummaryrefslogtreecommitdiff
path: root/utils/meta/pagination.go
blob: d0dda0885bea8949597e52b3d9399c16e3a344a2 (plain)
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
package meta

import (
	"strconv"

	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"
)

type Pagination struct {
	Page    int
	PerPage int
}

type PaginatedResponse struct {
	Items      any   `json:"items"`
	Total      int64 `json:"total"`
	Page       int   `json:"page"`
	PerPage    int   `json:"per_page"`
	TotalPages int   `json:"total_pages"`
}

func Paginate(context *fiber.Ctx) Pagination {
	requestData := Request(context)

	page := DefaultPage
	perPage := DefaultPerPage

	if pageValue := requestData.Query("page"); pageValue != "" {
		parsed, _ := strconv.Atoi(pageValue)
		if parsed >= DefaultPage {
			page = parsed
		}
	}

	if perPageValue := requestData.Query("per_page"); perPageValue != "" {
		parsed, _ := strconv.Atoi(perPageValue)
		if parsed >= DefaultPage && parsed <= MaxPerPage {
			perPage = parsed
		}
	}

	return Pagination{Page: page, PerPage: perPage}
}

func (self Pagination) Apply(query *gorm.DB) *gorm.DB {
	return query.Offset((self.Page - 1) * self.PerPage).Limit(self.PerPage)
}

func (self Pagination) Response(items any, total int64) PaginatedResponse {
	totalPages := int(total) / self.PerPage
	if int(total)%self.PerPage > 0 {
		totalPages++
	}

	return PaginatedResponse{
		Items:      items,
		Total:      total,
		Page:       self.Page,
		PerPage:    self.PerPage,
		TotalPages: totalPages,
	}
}