owl-blogs/web/utils.go

54 lines
984 B
Go
Raw Normal View History

2023-07-17 18:44:59 +00:00
package web
import (
"owl-blogs/app/repository"
"owl-blogs/config"
2023-07-17 18:44:59 +00:00
"owl-blogs/domain/model"
2023-07-27 20:02:13 +00:00
"strconv"
"github.com/gofiber/fiber/v2"
2023-07-17 18:44:59 +00:00
)
func getSiteConfig(repo repository.ConfigRepository) model.SiteConfig {
siteConfig := model.SiteConfig{}
err := repo.Get(config.SITE_CONFIG, &siteConfig)
2023-07-17 18:44:59 +00:00
if err != nil {
panic(err)
}
return siteConfig
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,
}
}