From fb257666aa69e4811abb32a7441a2d05fd082f0c Mon Sep 17 00:00:00 2001 From: Elias Kohout Date: Tue, 7 Jan 2025 11:40:59 +0100 Subject: [PATCH] add limit to index page, for performance improvements --- cmd/frontend/Index.go | 37 +++++++++++++++-------------- internal/model/database/articles.go | 5 ++-- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/cmd/frontend/Index.go b/cmd/frontend/Index.go index ccf46ac..63c501b 100644 --- a/cmd/frontend/Index.go +++ b/cmd/frontend/Index.go @@ -6,25 +6,26 @@ import ( "net/http" ) -// 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) { - // get articles - articles, err := app.articles.All() - if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError); return; } + // get articles + articles, err := app.articles.All(10) + if err != nil { + http.Error(w, err.Error(), 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()) + } - // 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; } + // 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 + } } diff --git a/internal/model/database/articles.go b/internal/model/database/articles.go index 3f2555e..bb3c2e4 100644 --- a/internal/model/database/articles.go +++ b/internal/model/database/articles.go @@ -11,13 +11,14 @@ type ArticleModel struct { // Gets all the article objects from the database. This may throw an error if // the connection to the database fails. -func (m *ArticleModel) All() ([]model.Article, error) { +func (m *ArticleModel) All(limit int) ([]model.Article, error) { stmt := ` SELECT id, title, sourceUrl, author, content, publishDate, fetchDate FROM articles ORDER BY publishDate DESC + LIMIT $1 ` - rows, err := m.DB.Query(stmt) + rows, err := m.DB.Query(stmt, limit) if err != nil { return nil, err }