saasitone/pkg/controller/pager.go

81 lines
1.8 KiB
Go
Raw Normal View History

package controller
2021-12-03 04:20:01 -08:00
import (
"math"
"strconv"
"github.com/labstack/echo/v4"
)
const (
// DefaultItemsPerPage stores the default amount of items per page
DefaultItemsPerPage = 20
2021-12-18 15:08:04 -08:00
// PageQueryKey stores the query key used to indicate the current page
PageQueryKey = "page"
)
2021-12-18 15:08:04 -08:00
// Pager provides a mechanism to allow a user to page results via a query parameter
2021-12-03 04:20:01 -08:00
type Pager struct {
2021-12-18 15:08:04 -08:00
// Items stores the total amount of items in the result set
Items int
// Page stores the current page number
Page int
// ItemsPerPage stores the amount of items to display per page
2021-12-03 04:20:01 -08:00
ItemsPerPage int
2021-12-18 15:08:04 -08:00
// Pages stores the total amount of pages in the result set
Pages int
2021-12-03 04:20:01 -08:00
}
2021-12-18 15:08:04 -08:00
// NewPager creates a new Pager
func NewPager(ctx echo.Context, itemsPerPage int) Pager {
2021-12-03 04:20:01 -08:00
p := Pager{
2021-12-18 15:08:04 -08:00
ItemsPerPage: itemsPerPage,
2021-12-03 04:20:01 -08:00
Page: 1,
}
2021-12-18 15:08:04 -08:00
if page := ctx.QueryParam(PageQueryKey); page != "" {
if pageInt, err := strconv.Atoi(page); err == nil {
2021-12-03 04:20:01 -08:00
if pageInt > 0 {
p.Page = pageInt
}
}
}
return p
}
2021-12-18 15:08:04 -08:00
// SetItems sets the amount of items in total for the pager and calculate the amount
// of total pages based off on the item per page.
// This should be used rather than setting either items or pages directly.
2021-12-03 04:20:01 -08:00
func (p *Pager) SetItems(items int) {
p.Items = items
p.Pages = int(math.Ceil(float64(items) / float64(p.ItemsPerPage)))
if p.Page > p.Pages {
p.Page = p.Pages
}
}
2021-12-18 15:08:04 -08:00
// IsBeginning determines if the pager is at the beginning of the pages
2021-12-24 14:58:53 -08:00
func (p Pager) IsBeginning() bool {
2021-12-03 04:20:01 -08:00
return p.Page == 1
}
2021-12-18 15:08:04 -08:00
// IsEnd determines if the pager is at the end of the pages
2021-12-24 14:58:53 -08:00
func (p Pager) IsEnd() bool {
2021-12-03 04:20:01 -08:00
return p.Page >= p.Pages
}
2021-12-18 15:08:04 -08:00
// GetOffset determines the offset of the results in order to get the items for
// the current page
2021-12-24 14:58:53 -08:00
func (p Pager) GetOffset() int {
2021-12-03 04:20:01 -08:00
if p.Page == 0 {
p.Page = 1
}
return (p.Page - 1) * p.ItemsPerPage
}