Complete CRUD operations for habits
Implement all missing endpoints for full habit management:
- GET /api/v1/habits - List all user habits
- GET /api/v1/habits/{id} - Get specific habit
- PUT /api/v1/habits/{id} - Update habit
- DELETE /api/v1/habits/{id} - Archive habit (soft delete)
- GET /api/v1/habits/{id}/entries - Get habit entry history
- DELETE /api/v1/habits/{id}/entries/{date} - Unmark habit (soft delete entry)
All endpoints include:
- TDD approach with comprehensive test coverage
- JWT authentication and ownership validation
- Proper error handling (404, 403, 400, 500)
- Clean architecture with separated commands/queries
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"apocapoc-api/internal/domain/repositories"
|
||||
"apocapoc-api/internal/shared/errors"
|
||||
)
|
||||
|
||||
type UpdateHabitCommand struct {
|
||||
HabitID string
|
||||
UserID string
|
||||
Name string
|
||||
Description string
|
||||
CarryOver bool
|
||||
TargetValue *float64
|
||||
SpecificDays []int
|
||||
SpecificDates []int
|
||||
}
|
||||
|
||||
type UpdateHabitHandler struct {
|
||||
habitRepo repositories.HabitRepository
|
||||
}
|
||||
|
||||
func NewUpdateHabitHandler(habitRepo repositories.HabitRepository) *UpdateHabitHandler {
|
||||
return &UpdateHabitHandler{
|
||||
habitRepo: habitRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *UpdateHabitHandler) Handle(ctx context.Context, cmd UpdateHabitCommand) error {
|
||||
// Validate input
|
||||
if strings.TrimSpace(cmd.Name) == "" {
|
||||
return errors.ErrInvalidInput
|
||||
}
|
||||
|
||||
// Find existing habit
|
||||
habit, err := h.habitRepo.FindByID(ctx, cmd.HabitID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check ownership
|
||||
if habit.UserID != cmd.UserID {
|
||||
return errors.ErrUnauthorized
|
||||
}
|
||||
|
||||
// Cannot update archived habits
|
||||
if !habit.IsActive() {
|
||||
return errors.ErrInvalidInput
|
||||
}
|
||||
|
||||
// Update fields
|
||||
habit.Name = cmd.Name
|
||||
habit.Description = cmd.Description
|
||||
habit.CarryOver = cmd.CarryOver
|
||||
habit.TargetValue = cmd.TargetValue
|
||||
habit.SpecificDays = cmd.SpecificDays
|
||||
habit.SpecificDates = cmd.SpecificDates
|
||||
|
||||
// Save changes
|
||||
return h.habitRepo.Update(ctx, habit)
|
||||
}
|
||||
Reference in New Issue
Block a user