2025-01-02 15:05:20 +01:00
|
|
|
package routes
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"crowsnest/internal/data"
|
|
|
|
|
"crowsnest/internal/model"
|
|
|
|
|
"crowsnest/internal/viewmodel"
|
|
|
|
|
"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 Index(w http.ResponseWriter, req *http.Request) {
|
|
|
|
|
// retrieve from repo
|
2025-01-02 15:13:13 +01:00
|
|
|
fds, err := data.NewFileDatastore("persistence/spiegel100.json")
|
2025-01-02 15:05:20 +01:00
|
|
|
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([]*viewmodel.ArticleViewModel, 0, len(articles))
|
|
|
|
|
for _, a := range articles {
|
|
|
|
|
articleVMs = append(articleVMs, viewmodel.NewArticleViewModel(a))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// render template
|
2025-01-02 15:13:13 +01:00
|
|
|
t := template.Must(template.ParseFiles("web/templates/article.html", "web/templates/layout.html"))
|
2025-01-02 15:05:20 +01:00
|
|
|
err = t.ExecuteTemplate(w, "base", articleVMs)
|
|
|
|
|
if err != nil { http.Error(w, "Failed to render template", http.StatusInternalServerError); return; }
|
|
|
|
|
}
|