Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pagination for projects API #664

Merged
merged 1 commit into from
Apr 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading