2023-06-25 19:32:36 +00:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"owl-blogs/app"
|
2023-07-13 19:20:00 +00:00
|
|
|
"owl-blogs/domain/model"
|
2023-07-09 17:51:49 +00:00
|
|
|
"owl-blogs/render"
|
2023-07-13 18:39:24 +00:00
|
|
|
"sort"
|
2023-07-13 19:20:00 +00:00
|
|
|
"strconv"
|
2023-06-25 19:32:36 +00:00
|
|
|
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
type IndexHandler struct {
|
|
|
|
entrySvc *app.EntryService
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewIndexHandler(entryService *app.EntryService) *IndexHandler {
|
|
|
|
return &IndexHandler{entrySvc: entryService}
|
|
|
|
}
|
|
|
|
|
2023-07-13 19:20:00 +00:00
|
|
|
type indexRenderData struct {
|
|
|
|
Entries []model.Entry
|
|
|
|
Page int
|
|
|
|
NextPage int
|
|
|
|
PrevPage int
|
|
|
|
FirstPage bool
|
|
|
|
LastPage bool
|
|
|
|
}
|
|
|
|
|
2023-06-25 19:32:36 +00:00
|
|
|
func (h *IndexHandler) Handle(c *fiber.Ctx) error {
|
2023-07-09 17:51:49 +00:00
|
|
|
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
|
|
|
|
entries, err := h.entrySvc.FindAll()
|
2023-07-13 19:20:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-07-09 17:51:49 +00:00
|
|
|
|
2023-07-13 18:39:24 +00:00
|
|
|
// sort entries by date descending
|
|
|
|
sort.Slice(entries, func(i, j int) bool {
|
|
|
|
return entries[i].PublishedAt().After(*entries[j].PublishedAt())
|
|
|
|
})
|
|
|
|
|
2023-07-13 19:20:00 +00:00
|
|
|
// pagination
|
|
|
|
page := c.Query("page")
|
|
|
|
if page == "" {
|
|
|
|
page = "1"
|
|
|
|
}
|
|
|
|
pageNum, err := strconv.Atoi(page)
|
|
|
|
if err != nil {
|
|
|
|
pageNum = 1
|
|
|
|
}
|
|
|
|
limit := 10
|
|
|
|
offset := (pageNum - 1) * limit
|
|
|
|
lastPage := false
|
|
|
|
if offset > len(entries) {
|
|
|
|
offset = len(entries)
|
|
|
|
lastPage = true
|
|
|
|
}
|
|
|
|
if offset+limit > len(entries) {
|
|
|
|
limit = len(entries) - offset
|
|
|
|
lastPage = true
|
|
|
|
}
|
|
|
|
entries = entries[offset : offset+limit]
|
|
|
|
|
2023-07-09 17:51:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-07-13 19:20:00 +00:00
|
|
|
return render.RenderTemplateWithBase(c, "views/index", indexRenderData{
|
|
|
|
Entries: entries,
|
|
|
|
Page: pageNum,
|
|
|
|
NextPage: pageNum + 1,
|
|
|
|
PrevPage: pageNum - 1,
|
|
|
|
FirstPage: pageNum == 1,
|
|
|
|
LastPage: lastPage,
|
|
|
|
})
|
2023-07-09 17:51:49 +00:00
|
|
|
|
2023-06-25 19:32:36 +00:00
|
|
|
}
|