Improve type safety with proper value objects for HabitType and Frequency

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
This commit is contained in:
2025-11-27 00:39:45 +01:00
parent 7768037724
commit ca2533d4df
11 changed files with 284 additions and 54 deletions
@@ -13,8 +13,8 @@ type CreateHabitCommand struct {
UserID string UserID string
Name string Name string
Description string Description string
Type string Type value_objects.HabitType
Frequency string Frequency value_objects.Frequency
SpecificDays []int SpecificDays []int
SpecificDates []int SpecificDates []int
CarryOver bool CarryOver bool
@@ -30,25 +30,23 @@ func NewCreateHabitHandler(habitRepo repositories.HabitRepository) *CreateHabitH
} }
func (h *CreateHabitHandler) Handle(ctx context.Context, cmd CreateHabitCommand) (string, error) { func (h *CreateHabitHandler) Handle(ctx context.Context, cmd CreateHabitCommand) (string, error) {
habitType := value_objects.HabitType(cmd.Type) if !cmd.Type.IsValid() {
if !habitType.IsValid() {
return "", errors.ErrInvalidInput return "", errors.ErrInvalidInput
} }
frequency := value_objects.Frequency(cmd.Frequency) if !cmd.Frequency.IsValid() {
if !frequency.IsValid() {
return "", errors.ErrInvalidInput return "", errors.ErrInvalidInput
} }
if frequency == value_objects.FrequencyWeekly && len(cmd.SpecificDays) == 0 { if cmd.Frequency == value_objects.FrequencyWeekly && len(cmd.SpecificDays) == 0 {
return "", errors.ErrInvalidInput return "", errors.ErrInvalidInput
} }
if frequency == value_objects.FrequencyMonthly && len(cmd.SpecificDates) == 0 { if cmd.Frequency == value_objects.FrequencyMonthly && len(cmd.SpecificDates) == 0 {
return "", errors.ErrInvalidInput return "", errors.ErrInvalidInput
} }
habit := entities.NewHabit(cmd.UserID, cmd.Name, habitType, frequency, cmd.CarryOver) habit := entities.NewHabit(cmd.UserID, cmd.Name, cmd.Type, cmd.Frequency, cmd.CarryOver)
habit.Description = cmd.Description habit.Description = cmd.Description
habit.SpecificDays = cmd.SpecificDays habit.SpecificDays = cmd.SpecificDays
habit.SpecificDates = cmd.SpecificDates habit.SpecificDates = cmd.SpecificDates
@@ -35,8 +35,8 @@ func (h *GetHabitByIDHandler) Handle(ctx context.Context, query GetHabitByIDQuer
return &HabitDTO{ return &HabitDTO{
ID: habit.ID, ID: habit.ID,
Name: habit.Name, Name: habit.Name,
Type: string(habit.Type), Type: habit.Type,
Frequency: string(habit.Frequency), Frequency: habit.Frequency,
TargetValue: habit.TargetValue, TargetValue: habit.TargetValue,
CarryOver: habit.CarryOver, CarryOver: habit.CarryOver,
SpecificDays: habit.SpecificDays, SpecificDays: habit.SpecificDays,
@@ -53,7 +53,7 @@ func TestGetHabitByIDHandler_ReturnsHabitSuccessfully(t *testing.T) {
t.Errorf("Expected name 'Drink Water', got %s", result.Name) t.Errorf("Expected name 'Drink Water', got %s", result.Name)
} }
if result.Type != string(value_objects.HabitTypeValue) { if result.Type != value_objects.HabitTypeValue {
t.Errorf("Expected type %s, got %s", value_objects.HabitTypeValue, result.Type) t.Errorf("Expected type %s, got %s", value_objects.HabitTypeValue, result.Type)
} }
@@ -5,13 +5,14 @@ import (
"time" "time"
"apocapoc-api/internal/domain/repositories" "apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/domain/value_objects"
"apocapoc-api/internal/shared/utils" "apocapoc-api/internal/shared/utils"
) )
type TodaysHabitDTO struct { type TodaysHabitDTO struct {
ID string ID string
Name string Name string
Type string Type value_objects.HabitType
TargetValue *float64 TargetValue *float64
ScheduledDate time.Time ScheduledDate time.Time
IsCarriedOver bool IsCarriedOver bool
@@ -80,7 +81,7 @@ func (h *GetTodaysHabitsHandler) Handle(
result = append(result, TodaysHabitDTO{ result = append(result, TodaysHabitDTO{
ID: habit.ID, ID: habit.ID,
Name: habit.Name, Name: habit.Name,
Type: string(habit.Type), Type: habit.Type,
TargetValue: habit.TargetValue, TargetValue: habit.TargetValue,
ScheduledDate: query.Date, ScheduledDate: query.Date,
IsCarriedOver: !shouldAppear && habit.CarryOver, IsCarriedOver: !shouldAppear && habit.CarryOver,
@@ -4,13 +4,14 @@ import (
"context" "context"
"apocapoc-api/internal/domain/repositories" "apocapoc-api/internal/domain/repositories"
"apocapoc-api/internal/domain/value_objects"
) )
type HabitDTO struct { type HabitDTO struct {
ID string ID string
Name string Name string
Type string Type value_objects.HabitType
Frequency string Frequency value_objects.Frequency
TargetValue *float64 TargetValue *float64
CarryOver bool CarryOver bool
SpecificDays []int SpecificDays []int
@@ -41,8 +42,8 @@ func (h *GetUserHabitsHandler) Handle(ctx context.Context, query GetUserHabitsQu
result = append(result, HabitDTO{ result = append(result, HabitDTO{
ID: habit.ID, ID: habit.ID,
Name: habit.Name, Name: habit.Name,
Type: string(habit.Type), Type: habit.Type,
Frequency: string(habit.Frequency), Frequency: habit.Frequency,
TargetValue: habit.TargetValue, TargetValue: habit.TargetValue,
CarryOver: habit.CarryOver, CarryOver: habit.CarryOver,
SpecificDays: habit.SpecificDays, SpecificDays: habit.SpecificDays,
@@ -92,11 +92,11 @@ func TestGetUserHabitsHandler_IncludesAllHabitFields(t *testing.T) {
t.Errorf("Expected name 'Drink Water', got %s", result.Name) t.Errorf("Expected name 'Drink Water', got %s", result.Name)
} }
if result.Type != string(value_objects.HabitTypeValue) { if result.Type != value_objects.HabitTypeValue {
t.Errorf("Expected type %s, got %s", value_objects.HabitTypeValue, result.Type) t.Errorf("Expected type %s, got %s", value_objects.HabitTypeValue, result.Type)
} }
if result.Frequency != string(value_objects.FrequencyDaily) { if result.Frequency != value_objects.FrequencyDaily {
t.Errorf("Expected frequency %s, got %s", value_objects.FrequencyDaily, result.Frequency) t.Errorf("Expected frequency %s, got %s", value_objects.FrequencyDaily, result.Frequency)
} }
@@ -1,5 +1,10 @@
package value_objects package value_objects
import (
"encoding/json"
"fmt"
)
type Frequency string type Frequency string
const ( const (
@@ -15,3 +20,21 @@ func (f Frequency) IsValid() bool {
} }
return false return false
} }
func (f Frequency) MarshalJSON() ([]byte, error) {
return json.Marshal(string(f))
}
func (f *Frequency) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
*f = Frequency(s)
if !f.IsValid() {
return fmt.Errorf("invalid frequency: %s (must be DAILY, WEEKLY, or MONTHLY)", s)
}
return nil
}
@@ -0,0 +1,90 @@
package value_objects
import (
"encoding/json"
"testing"
)
func TestFrequency_MarshalJSON(t *testing.T) {
tests := []struct {
name string
frequency Frequency
expected string
}{
{"Daily", FrequencyDaily, `"DAILY"`},
{"Weekly", FrequencyWeekly, `"WEEKLY"`},
{"Monthly", FrequencyMonthly, `"MONTHLY"`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
data, err := json.Marshal(tt.frequency)
if err != nil {
t.Fatalf("Failed to marshal: %v", err)
}
if string(data) != tt.expected {
t.Errorf("Expected %s, got %s", tt.expected, string(data))
}
})
}
}
func TestFrequency_UnmarshalJSON(t *testing.T) {
tests := []struct {
name string
input string
expected Frequency
shouldErr bool
}{
{"Valid Daily", `"DAILY"`, FrequencyDaily, false},
{"Valid Weekly", `"WEEKLY"`, FrequencyWeekly, false},
{"Valid Monthly", `"MONTHLY"`, FrequencyMonthly, false},
{"Invalid frequency", `"YEARLY"`, "", true},
{"Empty string", `""`, "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var f Frequency
err := json.Unmarshal([]byte(tt.input), &f)
if tt.shouldErr {
if err == nil {
t.Error("Expected error but got none")
}
return
}
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if f != tt.expected {
t.Errorf("Expected %s, got %s", tt.expected, f)
}
})
}
}
func TestFrequency_JSONRoundTrip(t *testing.T) {
type testStruct struct {
Frequency Frequency `json:"frequency"`
}
original := testStruct{Frequency: FrequencyWeekly}
data, err := json.Marshal(original)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
var decoded testStruct
err = json.Unmarshal(data, &decoded)
if err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if decoded.Frequency != original.Frequency {
t.Errorf("Round trip failed: expected %s, got %s", original.Frequency, decoded.Frequency)
}
}
@@ -1,5 +1,10 @@
package value_objects package value_objects
import (
"encoding/json"
"fmt"
)
type HabitType string type HabitType string
const ( const (
@@ -15,3 +20,21 @@ func (ht HabitType) IsValid() bool {
} }
return false return false
} }
func (ht HabitType) MarshalJSON() ([]byte, error) {
return json.Marshal(string(ht))
}
func (ht *HabitType) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
*ht = HabitType(s)
if !ht.IsValid() {
return fmt.Errorf("invalid habit type: %s (must be BOOLEAN, COUNTER, or VALUE)", s)
}
return nil
}
@@ -0,0 +1,90 @@
package value_objects
import (
"encoding/json"
"testing"
)
func TestHabitType_MarshalJSON(t *testing.T) {
tests := []struct {
name string
habitType HabitType
expected string
}{
{"Boolean", HabitTypeBoolean, `"BOOLEAN"`},
{"Counter", HabitTypeCounter, `"COUNTER"`},
{"Value", HabitTypeValue, `"VALUE"`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
data, err := json.Marshal(tt.habitType)
if err != nil {
t.Fatalf("Failed to marshal: %v", err)
}
if string(data) != tt.expected {
t.Errorf("Expected %s, got %s", tt.expected, string(data))
}
})
}
}
func TestHabitType_UnmarshalJSON(t *testing.T) {
tests := []struct {
name string
input string
expected HabitType
shouldErr bool
}{
{"Valid Boolean", `"BOOLEAN"`, HabitTypeBoolean, false},
{"Valid Counter", `"COUNTER"`, HabitTypeCounter, false},
{"Valid Value", `"VALUE"`, HabitTypeValue, false},
{"Invalid type", `"INVALID"`, "", true},
{"Empty string", `""`, "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var ht HabitType
err := json.Unmarshal([]byte(tt.input), &ht)
if tt.shouldErr {
if err == nil {
t.Error("Expected error but got none")
}
return
}
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if ht != tt.expected {
t.Errorf("Expected %s, got %s", tt.expected, ht)
}
})
}
}
func TestHabitType_JSONRoundTrip(t *testing.T) {
type testStruct struct {
Type HabitType `json:"type"`
}
original := testStruct{Type: HabitTypeCounter}
data, err := json.Marshal(original)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
var decoded testStruct
err = json.Unmarshal(data, &decoded)
if err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if decoded.Type != original.Type {
t.Errorf("Round trip failed: expected %s, got %s", original.Type, decoded.Type)
}
}
+38 -34
View File
@@ -1,16 +1,20 @@
package http package http
import "time" import (
"time"
"apocapoc-api/internal/domain/value_objects"
)
type CreateHabitRequest struct { type CreateHabitRequest struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
Type string `json:"type"` Type value_objects.HabitType `json:"type"`
Frequency string `json:"frequency"` Frequency value_objects.Frequency `json:"frequency"`
SpecificDays []int `json:"specific_days,omitempty"` SpecificDays []int `json:"specific_days,omitempty"`
SpecificDates []int `json:"specific_dates,omitempty"` SpecificDates []int `json:"specific_dates,omitempty"`
CarryOver bool `json:"carry_over"` CarryOver bool `json:"carry_over"`
TargetValue *float64 `json:"target_value,omitempty"` TargetValue *float64 `json:"target_value,omitempty"`
} }
type UpdateHabitRequest struct { type UpdateHabitRequest struct {
@@ -23,18 +27,18 @@ type UpdateHabitRequest struct {
} }
type HabitResponse struct { type HabitResponse struct {
ID string `json:"id"` ID string `json:"id"`
UserID string `json:"user_id"` UserID string `json:"user_id"`
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
Type string `json:"type"` Type value_objects.HabitType `json:"type"`
Frequency string `json:"frequency"` Frequency value_objects.Frequency `json:"frequency"`
SpecificDays []int `json:"specific_days,omitempty"` SpecificDays []int `json:"specific_days,omitempty"`
SpecificDates []int `json:"specific_dates,omitempty"` SpecificDates []int `json:"specific_dates,omitempty"`
CarryOver bool `json:"carry_over"` CarryOver bool `json:"carry_over"`
TargetValue *float64 `json:"target_value,omitempty"` TargetValue *float64 `json:"target_value,omitempty"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
ArchivedAt *time.Time `json:"archived_at,omitempty"` ArchivedAt *time.Time `json:"archived_at,omitempty"`
} }
type MarkHabitRequest struct { type MarkHabitRequest struct {
@@ -43,22 +47,22 @@ type MarkHabitRequest struct {
} }
type TodaysHabitResponse struct { type TodaysHabitResponse struct {
ID string `json:"id"` ID string `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Type string `json:"type"` Type value_objects.HabitType `json:"type"`
TargetValue *float64 `json:"target_value,omitempty"` TargetValue *float64 `json:"target_value,omitempty"`
ScheduledDate time.Time `json:"scheduled_date"` ScheduledDate time.Time `json:"scheduled_date"`
IsCarriedOver bool `json:"is_carried_over"` IsCarriedOver bool `json:"is_carried_over"`
} }
type UserHabitResponse struct { type UserHabitResponse struct {
ID string `json:"id"` ID string `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Type string `json:"type"` Type value_objects.HabitType `json:"type"`
Frequency string `json:"frequency"` Frequency value_objects.Frequency `json:"frequency"`
SpecificDays []int `json:"specific_days,omitempty"` SpecificDays []int `json:"specific_days,omitempty"`
TargetValue *float64 `json:"target_value,omitempty"` TargetValue *float64 `json:"target_value,omitempty"`
CarryOver bool `json:"carry_over"` CarryOver bool `json:"carry_over"`
} }
type HabitEntryResponse struct { type HabitEntryResponse struct {