Add pagination support to GET /api/v1/habits endpoint

- Create pagination package with Params and Response structs
- Add FindActiveByUserIDWithPagination and CountActiveByUserID methods to HabitRepository interface
- Implement pagination in SQLite repository using LIMIT and OFFSET
- Update GetUserHabitsHandler to support optional pagination parameters
- Modify HTTP endpoint to parse 'page' and 'page_size' query params (default: page=1, page_size=50, max=100)
- Add GetUserHabitsResponse DTO with pagination metadata
- Maintain backward compatibility - endpoint works with and without pagination params
- Add comprehensive tests for pagination logic in repository, handler, and pagination package
- Update all mock repositories to implement new pagination methods
This commit is contained in:
2025-12-01 23:53:00 +01:00
parent f780c69806
commit 38e640c617
21 changed files with 774 additions and 41 deletions
+6
View File
@@ -4,6 +4,7 @@ import (
"time"
"apocapoc-api/internal/domain/value_objects"
"apocapoc-api/internal/shared/pagination"
)
type CreateHabitRequest struct {
@@ -76,6 +77,11 @@ type UserHabitResponse struct {
IsNegative bool `json:"is_negative"`
}
type GetUserHabitsResponse struct {
Data []UserHabitResponse `json:"data"`
Pagination *pagination.Response `json:"pagination,omitempty"`
}
type HabitEntryResponse struct {
ID string `json:"id"`
HabitID string `json:"habit_id"`
+41 -7
View File
@@ -11,6 +11,7 @@ import (
"apocapoc-api/internal/application/queries"
"apocapoc-api/internal/i18n"
"apocapoc-api/internal/shared/errors"
"apocapoc-api/internal/shared/pagination"
"github.com/go-chi/chi/v5"
)
@@ -108,11 +109,13 @@ func (h *HabitHandlers) CreateHabit(w http.ResponseWriter, r *http.Request) {
// GetUserHabits godoc
// @Summary Get all user habits
// @Description Get all active habits for the authenticated user
// @Description Get all active habits for the authenticated user with optional pagination
// @Tags habits
// @Produce json
// @Security BearerAuth
// @Success 200 {array} UserHabitResponse
// @Param page query int false "Page number (default: 1)"
// @Param page_size query int false "Page size (default: 50, max: 100)"
// @Success 200 {object} GetUserHabitsResponse
// @Failure 401 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /habits [get]
@@ -127,15 +130,38 @@ func (h *HabitHandlers) GetUserHabits(w http.ResponseWriter, r *http.Request) {
UserID: userID,
}
habits, err := h.getUserHabitsHandler.Handle(r.Context(), query)
pageStr := r.URL.Query().Get("page")
pageSizeStr := r.URL.Query().Get("page_size")
if pageStr != "" || pageSizeStr != "" {
page := 1
pageSize := 50
if pageStr != "" {
if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
page = p
}
}
if pageSizeStr != "" {
if ps, err := strconv.Atoi(pageSizeStr); err == nil && ps > 0 {
pageSize = ps
}
}
params := pagination.NewParams(page, pageSize)
query.PaginationParams = &params
}
result, err := h.getUserHabitsHandler.Handle(r.Context(), query)
if err != nil {
respondErrorI18n(w, r, h.translator, http.StatusInternalServerError, "failed_get_habits")
return
}
response := make([]UserHabitResponse, len(habits))
for i, habit := range habits {
response[i] = UserHabitResponse{
habitResponses := make([]UserHabitResponse, len(result.Habits))
for i, habit := range result.Habits {
habitResponses[i] = UserHabitResponse{
ID: habit.ID,
Name: habit.Name,
Type: habit.Type,
@@ -147,7 +173,15 @@ func (h *HabitHandlers) GetUserHabits(w http.ResponseWriter, r *http.Request) {
}
}
respondJSON(w, http.StatusOK, response)
if result.Pagination != nil {
response := GetUserHabitsResponse{
Data: habitResponses,
Pagination: result.Pagination,
}
respondJSON(w, http.StatusOK, response)
} else {
respondJSON(w, http.StatusOK, habitResponses)
}
}
// GetHabitByID godoc
@@ -8,6 +8,7 @@ import (
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/shared/errors"
"apocapoc-api/internal/shared/pagination"
"github.com/google/uuid"
)
@@ -245,3 +246,39 @@ func (r *HabitRepository) Delete(ctx context.Context, id string) error {
return nil
}
func (r *HabitRepository) FindActiveByUserIDWithPagination(ctx context.Context, userID string, params pagination.Params) ([]*entities.Habit, error) {
query := `
SELECT id, user_id, name, description, type, frequency,
specific_days, specific_dates, carry_over, is_negative, target_value,
created_at, archived_at
FROM habits
WHERE user_id = ? AND archived_at IS NULL
ORDER BY created_at DESC
LIMIT ? OFFSET ?
`
rows, err := r.db.QueryContext(ctx, query, userID, params.Limit(), params.Offset())
if err != nil {
return nil, fmt.Errorf("failed to find habits: %w", err)
}
defer rows.Close()
return r.scanHabits(rows)
}
func (r *HabitRepository) CountActiveByUserID(ctx context.Context, userID string) (int, error) {
query := `
SELECT COUNT(*)
FROM habits
WHERE user_id = ? AND archived_at IS NULL
`
var count int
err := r.db.QueryRowContext(ctx, query, userID).Scan(&count)
if err != nil {
return 0, fmt.Errorf("failed to count habits: %w", err)
}
return count, nil
}
@@ -8,6 +8,7 @@ import (
"apocapoc-api/internal/domain/entities"
"apocapoc-api/internal/domain/value_objects"
"apocapoc-api/internal/shared/errors"
"apocapoc-api/internal/shared/pagination"
)
func TestHabitRepositoryCreate(t *testing.T) {
@@ -262,3 +263,162 @@ func TestHabitRepositoryArchive(t *testing.T) {
t.Error("Expected habit to be archived")
}
}
func TestHabitRepositoryFindActiveByUserIDWithPagination(t *testing.T) {
db := setupTestDB(t)
defer db.Close()
repo := NewHabitRepository(db)
ctx := context.Background()
userID := "user-pagination-test"
for i := 1; i <= 10; i++ {
habit := entities.NewHabit(
userID,
"Habit "+string(rune(i+'0')),
value_objects.HabitTypeBoolean,
value_objects.FrequencyDaily,
false,
false,
)
err := repo.Create(ctx, habit)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
time.Sleep(1 * time.Millisecond)
}
now := time.Now()
allHabits, _ := repo.FindActiveByUserID(ctx, userID)
allHabits[0].ArchivedAt = &now
repo.Update(ctx, allHabits[0])
t.Run("FirstPage", func(t *testing.T) {
params := pagination.NewParams(1, 5)
habits, err := repo.FindActiveByUserIDWithPagination(ctx, userID, params)
if err != nil {
t.Fatalf("FindActiveByUserIDWithPagination failed: %v", err)
}
if len(habits) != 5 {
t.Errorf("Expected 5 habits on first page, got %d", len(habits))
}
})
t.Run("SecondPage", func(t *testing.T) {
params := pagination.NewParams(2, 5)
habits, err := repo.FindActiveByUserIDWithPagination(ctx, userID, params)
if err != nil {
t.Fatalf("FindActiveByUserIDWithPagination failed: %v", err)
}
if len(habits) != 4 {
t.Errorf("Expected 4 habits on second page (9 total active), got %d", len(habits))
}
})
t.Run("PageBeyondTotal", func(t *testing.T) {
params := pagination.NewParams(10, 5)
habits, err := repo.FindActiveByUserIDWithPagination(ctx, userID, params)
if err != nil {
t.Fatalf("FindActiveByUserIDWithPagination failed: %v", err)
}
if len(habits) != 0 {
t.Errorf("Expected 0 habits beyond total pages, got %d", len(habits))
}
})
t.Run("CustomPageSize", func(t *testing.T) {
params := pagination.NewParams(1, 3)
habits, err := repo.FindActiveByUserIDWithPagination(ctx, userID, params)
if err != nil {
t.Fatalf("FindActiveByUserIDWithPagination failed: %v", err)
}
if len(habits) != 3 {
t.Errorf("Expected 3 habits with page_size=3, got %d", len(habits))
}
})
t.Run("ExcludesArchived", func(t *testing.T) {
params := pagination.NewParams(1, 20)
habits, err := repo.FindActiveByUserIDWithPagination(ctx, userID, params)
if err != nil {
t.Fatalf("FindActiveByUserIDWithPagination failed: %v", err)
}
if len(habits) != 9 {
t.Errorf("Expected 9 active habits (1 archived), got %d", len(habits))
}
for _, habit := range habits {
if habit.ArchivedAt != nil {
t.Error("Expected no archived habits in results")
}
}
})
}
func TestHabitRepositoryCountActiveByUserID(t *testing.T) {
db := setupTestDB(t)
defer db.Close()
repo := NewHabitRepository(db)
ctx := context.Background()
userID := "user-count-test"
t.Run("NoHabits", func(t *testing.T) {
count, err := repo.CountActiveByUserID(ctx, "non-existent-user")
if err != nil {
t.Fatalf("CountActiveByUserID failed: %v", err)
}
if count != 0 {
t.Errorf("Expected count 0 for non-existent user, got %d", count)
}
})
for i := 1; i <= 7; i++ {
habit := entities.NewHabit(
userID,
"Habit "+string(rune(i+'0')),
value_objects.HabitTypeBoolean,
value_objects.FrequencyDaily,
false,
false,
)
repo.Create(ctx, habit)
}
t.Run("AllActive", func(t *testing.T) {
count, err := repo.CountActiveByUserID(ctx, userID)
if err != nil {
t.Fatalf("CountActiveByUserID failed: %v", err)
}
if count != 7 {
t.Errorf("Expected count 7, got %d", count)
}
})
t.Run("WithArchived", func(t *testing.T) {
habits, _ := repo.FindActiveByUserID(ctx, userID)
now := time.Now()
habits[0].ArchivedAt = &now
habits[1].ArchivedAt = &now
repo.Update(ctx, habits[0])
repo.Update(ctx, habits[1])
count, err := repo.CountActiveByUserID(ctx, userID)
if err != nil {
t.Fatalf("CountActiveByUserID failed: %v", err)
}
if count != 5 {
t.Errorf("Expected count 5 (7 total - 2 archived), got %d", count)
}
})
}