summaryrefslogtreecommitdiff
path: root/shrine/utils/meta/pagination.go
blob: 8b559bf37227f1b7503e0f4114179daf5906d7be (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
package meta

import (
	"shrine/types/common"
	"strconv"

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

type Pagination struct {
	Page    int
	PerPage int
}

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

	pageStr, _ := request.Query("page")
	page, _ := strconv.Atoi(pageStr)
	if page < 1 {
		page = 1
	}

	perPageStr, _ := request.Query("per_page")
	perPage, _ := strconv.Atoi(perPageStr)
	if perPage < 1 || perPage > 50 {
		perPage = 20
	}

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

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

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

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