Skip to content

Commit

Permalink
Add pagination for projects API (#664)
Browse files Browse the repository at this point in the history
  • Loading branch information
jfreda authored Apr 2, 2024
1 parent 76f03a6 commit 913dece
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions internal/api/v2/projects.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
)

const (
defaultHitsPerPage = 24
MaxRecentlyViewedProjects = 10
)

Expand Down Expand Up @@ -76,9 +77,35 @@ func ProjectsHandler(srv server.Server) http.Handler {

// Get query parameters.
q := r.URL.Query()
hitsPerPageParam := q.Get("hitsPerPage")
pageParam := q.Get("page")
statusParam := q.Get("status")
titleParam := q.Get("title")

// Set default values for page and hitsPerPage parameters.
page := 1
hitsPerPage := defaultHitsPerPage

// Parse page parameter.
if pageParam != "" {
p, err := strconv.Atoi(pageParam)
if err != nil {
http.Error(w, "Invalid page parameter", http.StatusBadRequest)
return
}
page = p
}

// Parse perPage parameter.
if hitsPerPageParam != "" {
hpp, err := strconv.Atoi(hitsPerPageParam)
if err != nil {
http.Error(w, "Invalid hitsPerPage parameter", http.StatusBadRequest)
return
}
hitsPerPage = hpp
}

// Build status condition for database query.
var cond models.Project
if statusParam != "" {
Expand All @@ -96,8 +123,11 @@ func ProjectsHandler(srv server.Server) http.Handler {

// Get projects from database.
projs := []models.Project{}
offset := (page - 1) * hitsPerPage
if err := srv.DB.
Where("title ILIKE ?", fmt.Sprintf("%%%s%%", titleParam)).
Offset(offset).
Limit(hitsPerPage).
Find(&projs, cond).
Error; err != nil &&
!errors.Is(err, gorm.ErrRecordNotFound) {
Expand Down

0 comments on commit 913dece

Please sign in to comment.