add limit to index page, for performance improvements

This commit is contained in:
2025-01-07 11:40:59 +01:00
parent d5f934783b
commit fb257666aa
2 changed files with 22 additions and 20 deletions

View File

@@ -8,23 +8,24 @@ import (
// List the latest articles using the base template. // List the latest articles using the base template.
func (app *App) Index(w http.ResponseWriter, req *http.Request) { func (app *App) Index(w http.ResponseWriter, req *http.Request) {
// get articles // get articles
articles, err := app.articles.All() articles, err := app.articles.All(10)
if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError); return; } if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// truncate // convert to viewmodel
if len(articles) > 10 { articleVMs := make([]*model.ArticleViewModel, 0, len(articles))
articles = articles[:10] for _, a := range articles {
} articleVMs = append(articleVMs, a.ViewModel())
}
// convert to viewmodel // render template
articleVMs := make([]*model.ArticleViewModel, 0, len(articles)) t := template.Must(template.ParseFiles("assets/templates/article.html", "assets/templates/layout.html"))
for _, a := range articles { err = t.ExecuteTemplate(w, "base", articleVMs)
articleVMs = append(articleVMs, a.ViewModel()) if err != nil {
} http.Error(w, "Failed to render template", http.StatusInternalServerError)
return
// 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; }
} }

View File

@@ -11,13 +11,14 @@ type ArticleModel struct {
// Gets all the article objects from the database. This may throw an error if // Gets all the article objects from the database. This may throw an error if
// the connection to the database fails. // the connection to the database fails.
func (m *ArticleModel) All() ([]model.Article, error) { func (m *ArticleModel) All(limit int) ([]model.Article, error) {
stmt := ` stmt := `
SELECT id, title, sourceUrl, author, content, publishDate, fetchDate SELECT id, title, sourceUrl, author, content, publishDate, fetchDate
FROM articles FROM articles
ORDER BY publishDate DESC ORDER BY publishDate DESC
LIMIT $1
` `
rows, err := m.DB.Query(stmt) rows, err := m.DB.Query(stmt, limit)
if err != nil { if err != nil {
return nil, err return nil, err
} }