58 lines
1.0 KiB
Go
58 lines
1.0 KiB
Go
package shared
|
|
|
|
import (
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type PaginationInfo struct {
|
|
Limit int
|
|
Offset int
|
|
Total int
|
|
TotalPages int
|
|
CurrentPage int
|
|
HasNext bool
|
|
HasPrev bool
|
|
}
|
|
|
|
func ParseQueryLimit(c *gin.Context) int {
|
|
limit := 10 // default
|
|
l, err := strconv.Atoi(c.Query("limit"))
|
|
if err == nil {
|
|
if l > 100 {
|
|
limit = 100 // max limit default
|
|
} else if l < 100 && l > 0 {
|
|
limit = l
|
|
}
|
|
}
|
|
|
|
return limit
|
|
}
|
|
|
|
func ParseQueryOffset(c *gin.Context) int {
|
|
offset := 0
|
|
o, err := strconv.Atoi(c.Query("offset"))
|
|
if err == nil {
|
|
if o > 0 {
|
|
offset = o
|
|
}
|
|
}
|
|
return offset
|
|
}
|
|
|
|
func (source *PaginationInfo) CalculatePagingInfo() *PaginationInfo {
|
|
result := source
|
|
|
|
result.TotalPages, result.CurrentPage = 0, 1
|
|
if result.Limit > 0 {
|
|
result.TotalPages = (result.Total + result.Limit - 1) / result.Limit
|
|
result.CurrentPage = (result.Offset / result.Limit) + 1
|
|
}
|
|
|
|
result.HasNext = result.Offset+result.Limit < result.Total
|
|
result.HasPrev = result.Offset > 0
|
|
|
|
return result
|
|
}
|