restructuring

This commit is contained in:
2025-01-02 16:21:02 +01:00
parent f80889ff95
commit fbca771479
6 changed files with 66 additions and 54 deletions

41
cmd/frontend/Index.go Normal file
View File

@@ -0,0 +1,41 @@
package main
import (
"crowsnest/internal/data"
"crowsnest/internal/model"
"html/template"
"net/http"
)
// sort criteria
type articleDateOrder struct {}
func (ord articleDateOrder) Weight(a *model.Article) int {
return int(a.PublishDate.Unix())
}
// List the latest articles using the base template.
func (app *App) Index(w http.ResponseWriter, req *http.Request) {
// retrieve from repo
fds, err := data.NewFileDatastore("persistence/spiegel100.json")
if err != nil { http.Error(w, "Failed to load datastore", http.StatusInternalServerError); return; }
repo, err := data.NewDefaultRepository[*model.Article](fds, "article")
if err != nil { http.Error(w, "Failed to create repository", http.StatusInternalServerError); return; }
articles, err := repo.GetByCriteria(articleDateOrder{})
if err != nil { http.Error(w, "Failed to get articles", http.StatusInternalServerError); return; }
// truncate
if len(articles) > 10 {
articles = articles[:10]
}
// convert to viewmodel
articleVMs := make([]*model.ArticleViewModel, 0, len(articles))
for _, a := range articles {
articleVMs = append(articleVMs, a.ViewModel())
}
// render template
t := template.Must(template.ParseFiles("assets/templates/article.html", "assets/templates/layout.html"))
err = t.ExecuteTemplate(w, "base", articleVMs)
if err != nil { http.Error(w, "Failed to render template", http.StatusInternalServerError); return; }
}