ca2533d4df
Replace generic string types with strongly-typed value objects throughout the application layer. This change ensures compile-time type checking and automatic validation during JSON deserialization. Changes: - Add JSON marshaling/unmarshaling to HabitType and Frequency value objects - Update all DTOs to use typed fields instead of strings - Update commands and queries to use proper types - Remove unnecessary string conversions - Add comprehensive JSON serialization tests - Fix existing tests to work with typed fields Benefits: - Type safety: compiler catches invalid usage - Automatic validation: invalid values rejected during JSON parsing - Better code documentation and self-explanatory APIs - Reduced runtime errors
61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package commands
|
|
|
|
import (
|
|
"context"
|
|
|
|
"apocapoc-api/internal/domain/entities"
|
|
"apocapoc-api/internal/domain/repositories"
|
|
"apocapoc-api/internal/domain/value_objects"
|
|
"apocapoc-api/internal/shared/errors"
|
|
)
|
|
|
|
type CreateHabitCommand struct {
|
|
UserID string
|
|
Name string
|
|
Description string
|
|
Type value_objects.HabitType
|
|
Frequency value_objects.Frequency
|
|
SpecificDays []int
|
|
SpecificDates []int
|
|
CarryOver bool
|
|
TargetValue *float64
|
|
}
|
|
|
|
type CreateHabitHandler struct {
|
|
habitRepo repositories.HabitRepository
|
|
}
|
|
|
|
func NewCreateHabitHandler(habitRepo repositories.HabitRepository) *CreateHabitHandler {
|
|
return &CreateHabitHandler{habitRepo: habitRepo}
|
|
}
|
|
|
|
func (h *CreateHabitHandler) Handle(ctx context.Context, cmd CreateHabitCommand) (string, error) {
|
|
if !cmd.Type.IsValid() {
|
|
return "", errors.ErrInvalidInput
|
|
}
|
|
|
|
if !cmd.Frequency.IsValid() {
|
|
return "", errors.ErrInvalidInput
|
|
}
|
|
|
|
if cmd.Frequency == value_objects.FrequencyWeekly && len(cmd.SpecificDays) == 0 {
|
|
return "", errors.ErrInvalidInput
|
|
}
|
|
|
|
if cmd.Frequency == value_objects.FrequencyMonthly && len(cmd.SpecificDates) == 0 {
|
|
return "", errors.ErrInvalidInput
|
|
}
|
|
|
|
habit := entities.NewHabit(cmd.UserID, cmd.Name, cmd.Type, cmd.Frequency, cmd.CarryOver)
|
|
habit.Description = cmd.Description
|
|
habit.SpecificDays = cmd.SpecificDays
|
|
habit.SpecificDates = cmd.SpecificDates
|
|
habit.TargetValue = cmd.TargetValue
|
|
|
|
if err := h.habitRepo.Create(ctx, habit); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return habit.ID, nil
|
|
}
|