add pagination
This commit is contained in:
@@ -11,14 +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(limit int) ([]model.Article, error) {
|
||||
func (m *ArticleModel) All(limit int, offset int) ([]model.Article, error) {
|
||||
stmt := `
|
||||
SELECT id, title, sourceUrl, content, publishDate, fetchDate, aisummary
|
||||
FROM articles
|
||||
ORDER BY publishDate DESC
|
||||
LIMIT $1
|
||||
LIMIT $1 OFFSET $2
|
||||
`
|
||||
rows, err := m.DB.Query(stmt, limit)
|
||||
rows, err := m.DB.Query(stmt, limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -41,6 +41,21 @@ func (m *ArticleModel) All(limit int) ([]model.Article, error) {
|
||||
return articles, nil
|
||||
}
|
||||
|
||||
// Counts all articles in the database. This may throw an error if the
|
||||
// connection to the database fails.
|
||||
func (m *ArticleModel) CountAll() (uint, error) {
|
||||
stmt := `SELECT count(id) FROM articles `
|
||||
|
||||
rows := m.DB.QueryRow(stmt)
|
||||
|
||||
count := uint(0)
|
||||
if err := rows.Scan(&count); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// Will use the full-text search features of the underlying database to search
|
||||
// articles for a given search query. This may fail if the connection to the
|
||||
// database fails.
|
||||
|
||||
35
src/internal/model/pagination.go
Normal file
35
src/internal/model/pagination.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type PageButton struct {
|
||||
Content string
|
||||
Active bool
|
||||
Disabled bool
|
||||
}
|
||||
|
||||
type PaginationViewModel []PageButton
|
||||
|
||||
func NewPaginationViewModel(currentPage uint, totalPages uint) *PaginationViewModel {
|
||||
pagVM := make(PaginationViewModel, 0)
|
||||
|
||||
if totalPages > 1 {
|
||||
pagVM = append(pagVM, PageButton{"1", currentPage == 1, false})
|
||||
}
|
||||
if currentPage > 3 {
|
||||
pagVM = append(pagVM, PageButton{"...", false, true})
|
||||
}
|
||||
for i := max(2, currentPage-1); i <= min(totalPages-1, currentPage+1); i++ {
|
||||
pagVM = append(pagVM, PageButton{strconv.Itoa(int(i)), i == currentPage, false})
|
||||
}
|
||||
if currentPage < totalPages-2 {
|
||||
pagVM = append(pagVM, PageButton{"...", false, true})
|
||||
}
|
||||
if totalPages > 1 {
|
||||
pagVM = append(pagVM, PageButton{strconv.Itoa(int(totalPages)), totalPages == currentPage, false})
|
||||
}
|
||||
|
||||
return &pagVM
|
||||
}
|
||||
Reference in New Issue
Block a user