added: pagination package
This commit is contained in:
parent
995ea60f34
commit
6ea5edb017
2 changed files with 57 additions and 0 deletions
22
pkg/pagination/dto.go
Normal file
22
pkg/pagination/dto.go
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
package pagination
|
||||||
|
|
||||||
|
type QueryParams struct {
|
||||||
|
Query string
|
||||||
|
Page int
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
type Response struct {
|
||||||
|
Pagination Pagination `json:"pagination"`
|
||||||
|
Data any `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Pagination struct {
|
||||||
|
Page int `json:"page"`
|
||||||
|
PerPage int `json:"per_page"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
TotalPages int `json:"total_pages"`
|
||||||
|
HasNext bool `json:"has_next"`
|
||||||
|
HasPrev bool `json:"has_prev"`
|
||||||
|
OverallCount int `json:"overall_count,omitempty"`
|
||||||
|
}
|
||||||
35
pkg/pagination/handler.go
Normal file
35
pkg/pagination/handler.go
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
package pagination
|
||||||
|
|
||||||
|
import "math"
|
||||||
|
|
||||||
|
type Params struct {
|
||||||
|
Page int
|
||||||
|
PerPage int
|
||||||
|
TotalCount int
|
||||||
|
TotalPages int
|
||||||
|
OverallCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
func PrepareParams(params *Params) *Params {
|
||||||
|
totalPages := int(math.Ceil(float64(params.TotalCount) / float64(params.PerPage)))
|
||||||
|
params.TotalPages = totalPages
|
||||||
|
|
||||||
|
if params.Page > totalPages {
|
||||||
|
params.Page = totalPages
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
func PaginatedResponse(data any, params *Params) *Response {
|
||||||
|
pagination := Pagination{
|
||||||
|
Page: params.Page,
|
||||||
|
PerPage: params.PerPage,
|
||||||
|
Total: params.TotalCount,
|
||||||
|
TotalPages: params.TotalPages,
|
||||||
|
HasNext: params.Page < params.TotalPages,
|
||||||
|
HasPrev: params.Page > 1,
|
||||||
|
OverallCount: params.OverallCount,
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Response{Pagination: pagination, Data: data}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue