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

@@ -9,12 +9,10 @@ import (
// 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; }
// truncate
if len(articles) > 10 {
articles = articles[:10]
articles, err := app.articles.All(10)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// convert to viewmodel
@@ -26,5 +24,8 @@ func (app *App) Index(w http.ResponseWriter, req *http.Request) {
// 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; }
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
// 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
}