2023-07-17 18:44:59 +00:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
2023-07-27 20:02:13 +00:00
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"github.com/gofiber/fiber/v2"
|
2023-07-17 18:44:59 +00:00
|
|
|
)
|
|
|
|
|
2023-07-27 20:02:13 +00:00
|
|
|
type paginationData[T any] struct {
|
|
|
|
items []T
|
|
|
|
page uint
|
|
|
|
lastPage bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func paginate[T any](c *fiber.Ctx, items []T, limit int) paginationData[T] {
|
|
|
|
page := c.Query("page")
|
|
|
|
if page == "" {
|
|
|
|
page = "1"
|
|
|
|
}
|
|
|
|
pageNum, err := strconv.Atoi(page)
|
|
|
|
if err != nil {
|
|
|
|
pageNum = 1
|
|
|
|
}
|
|
|
|
offset := (pageNum - 1) * limit
|
|
|
|
lastPage := false
|
|
|
|
if offset > len(items) {
|
|
|
|
offset = len(items)
|
|
|
|
lastPage = true
|
|
|
|
}
|
|
|
|
if offset+limit > len(items) {
|
|
|
|
limit = len(items) - offset
|
|
|
|
lastPage = true
|
|
|
|
}
|
|
|
|
items = items[offset : offset+limit]
|
|
|
|
|
|
|
|
return paginationData[T]{
|
|
|
|
items: items,
|
|
|
|
page: uint(pageNum),
|
|
|
|
lastPage: lastPage,
|
|
|
|
}
|
|
|
|
}
|