build: /implement-feature user-preferences
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
This commit is contained in:
parent
2a25542f71
commit
a0ff64af5e
@ -1,7 +1,7 @@
|
|||||||
slug: user-preferences
|
slug: user-preferences
|
||||||
title: User Preferences API
|
title: User Preferences API
|
||||||
created: 2026-02-09T03:07:55.541048432Z
|
created: 2026-02-09T03:07:55.541048432Z
|
||||||
phase: ready
|
phase: implementation
|
||||||
phase_history:
|
phase_history:
|
||||||
- phase: draft
|
- phase: draft
|
||||||
entered: 2026-02-09T03:07:55.541048432Z
|
entered: 2026-02-09T03:07:55.541048432Z
|
||||||
@ -14,6 +14,9 @@ phase_history:
|
|||||||
exited: 2026-02-09T03:20:30.611901038Z
|
exited: 2026-02-09T03:20:30.611901038Z
|
||||||
- phase: ready
|
- phase: ready
|
||||||
entered: 2026-02-09T03:20:30.611901038Z
|
entered: 2026-02-09T03:20:30.611901038Z
|
||||||
|
exited: 2026-02-09T03:22:37.766271477Z
|
||||||
|
- phase: implementation
|
||||||
|
entered: 2026-02-09T03:22:37.766271477Z
|
||||||
artifacts:
|
artifacts:
|
||||||
audit:
|
audit:
|
||||||
status: pending
|
status: pending
|
||||||
@ -45,25 +48,40 @@ artifacts:
|
|||||||
approved_by: user
|
approved_by: user
|
||||||
approved_at: 2026-02-09T03:18:20.547304636Z
|
approved_at: 2026-02-09T03:18:20.547304636Z
|
||||||
total: 7
|
total: 7
|
||||||
|
completed: 7
|
||||||
tasks:
|
tasks:
|
||||||
- id: task-001
|
- id: task-001
|
||||||
title: Domain layer - UserPreferences model and domain errors
|
title: Domain layer - UserPreferences model and domain errors
|
||||||
status: pending
|
status: complete
|
||||||
|
started_at: 2026-02-09T03:22:45.05034374Z
|
||||||
|
done_at: 2026-02-09T03:23:09.596316012Z
|
||||||
- id: task-002
|
- id: task-002
|
||||||
title: Port layer - PreferenceRepository interface
|
title: Port layer - PreferenceRepository interface
|
||||||
status: pending
|
status: complete
|
||||||
|
started_at: 2026-02-09T03:23:15.366917585Z
|
||||||
|
done_at: 2026-02-09T03:23:28.228255343Z
|
||||||
- id: task-003
|
- id: task-003
|
||||||
title: Service layer - PreferenceService with validation logic and tests
|
title: Service layer - PreferenceService with validation logic and tests
|
||||||
status: pending
|
status: complete
|
||||||
|
started_at: 2026-02-09T03:23:34.579590762Z
|
||||||
|
done_at: 2026-02-09T03:24:56.650842143Z
|
||||||
- id: task-004
|
- id: task-004
|
||||||
title: Database migration and PostgreSQL adapter
|
title: Database migration and PostgreSQL adapter
|
||||||
status: pending
|
status: complete
|
||||||
|
started_at: 2026-02-09T03:25:05.810659873Z
|
||||||
|
done_at: 2026-02-09T03:25:35.931875082Z
|
||||||
- id: task-005
|
- id: task-005
|
||||||
title: HTTP handlers - GET and PUT preference endpoints with tests
|
title: HTTP handlers - GET and PUT preference endpoints with tests
|
||||||
status: pending
|
status: complete
|
||||||
|
started_at: 2026-02-09T03:25:41.767966428Z
|
||||||
|
done_at: 2026-02-09T03:27:06.980076413Z
|
||||||
- id: task-006
|
- id: task-006
|
||||||
title: Routes, OpenAPI spec, and main.go wiring
|
title: Routes, OpenAPI spec, and main.go wiring
|
||||||
status: pending
|
status: complete
|
||||||
|
started_at: 2026-02-09T03:27:14.505352647Z
|
||||||
|
done_at: 2026-02-09T03:28:39.057928335Z
|
||||||
- id: task-007
|
- id: task-007
|
||||||
title: Cleanup - Remove example scaffolding files
|
title: Cleanup - Remove example scaffolding files
|
||||||
status: pending
|
status: complete
|
||||||
|
started_at: 2026-02-09T03:28:46.479063131Z
|
||||||
|
done_at: 2026-02-09T03:29:25.590171477Z
|
||||||
|
|||||||
@ -4,10 +4,10 @@ project:
|
|||||||
active_work:
|
active_work:
|
||||||
features:
|
features:
|
||||||
- slug: user-preferences
|
- slug: user-preferences
|
||||||
phase: ready
|
phase: implementation
|
||||||
blocked: []
|
blocked: []
|
||||||
last_updated: 2026-02-09T03:20:30.626836394Z
|
last_updated: 2026-02-09T03:29:25.591047245Z
|
||||||
last_action: TRANSITION
|
last_action: COMPLETE_TASK
|
||||||
last_actor: cli
|
last_actor: cli
|
||||||
history:
|
history:
|
||||||
- timestamp: 2026-02-09T03:07:55.541429198Z
|
- timestamp: 2026-02-09T03:07:55.541429198Z
|
||||||
@ -50,3 +50,43 @@ history:
|
|||||||
feature: user-preferences
|
feature: user-preferences
|
||||||
actor: cli
|
actor: cli
|
||||||
result: success
|
result: success
|
||||||
|
- timestamp: 2026-02-09T03:22:37.76692675Z
|
||||||
|
action: TRANSITION
|
||||||
|
feature: user-preferences
|
||||||
|
actor: cli
|
||||||
|
result: success
|
||||||
|
- timestamp: 2026-02-09T03:23:09.597746864Z
|
||||||
|
action: COMPLETE_TASK
|
||||||
|
feature: user-preferences
|
||||||
|
actor: cli
|
||||||
|
result: success
|
||||||
|
- timestamp: 2026-02-09T03:23:28.229040239Z
|
||||||
|
action: COMPLETE_TASK
|
||||||
|
feature: user-preferences
|
||||||
|
actor: cli
|
||||||
|
result: success
|
||||||
|
- timestamp: 2026-02-09T03:24:56.651563771Z
|
||||||
|
action: COMPLETE_TASK
|
||||||
|
feature: user-preferences
|
||||||
|
actor: cli
|
||||||
|
result: success
|
||||||
|
- timestamp: 2026-02-09T03:25:35.93266556Z
|
||||||
|
action: COMPLETE_TASK
|
||||||
|
feature: user-preferences
|
||||||
|
actor: cli
|
||||||
|
result: success
|
||||||
|
- timestamp: 2026-02-09T03:27:06.98073376Z
|
||||||
|
action: COMPLETE_TASK
|
||||||
|
feature: user-preferences
|
||||||
|
actor: cli
|
||||||
|
result: success
|
||||||
|
- timestamp: 2026-02-09T03:28:39.058628874Z
|
||||||
|
action: COMPLETE_TASK
|
||||||
|
feature: user-preferences
|
||||||
|
actor: cli
|
||||||
|
result: success
|
||||||
|
- timestamp: 2026-02-09T03:29:25.591045923Z
|
||||||
|
action: COMPLETE_TASK
|
||||||
|
feature: user-preferences
|
||||||
|
actor: cli
|
||||||
|
result: success
|
||||||
|
|||||||
6
go.work
6
go.work
@ -1,5 +1,9 @@
|
|||||||
go 1.23
|
go 1.24.0
|
||||||
|
|
||||||
|
toolchain go1.24.13
|
||||||
|
|
||||||
use ./pkg
|
use ./pkg
|
||||||
|
|
||||||
use ./services/preferences-api
|
use ./services/preferences-api
|
||||||
|
|
||||||
// Component modules will be added below
|
// Component modules will be added below
|
||||||
|
|||||||
@ -2,17 +2,24 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"embed"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/app"
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/app"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/config"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/database"
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/adapter/memory"
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/adapter/postgres"
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/api"
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/api"
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service"
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//go:embed migrations/*.sql
|
||||||
|
var migrationsFS embed.FS
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Parse flags
|
// Parse flags
|
||||||
exportOpenAPI := flag.Bool("export-openapi", false, "Export OpenAPI spec to stdout and exit")
|
exportOpenAPI := flag.Bool("export-openapi", false, "Export OpenAPI spec to stdout and exit")
|
||||||
@ -33,17 +40,29 @@ func main() {
|
|||||||
// Create logger
|
// Create logger
|
||||||
logger := logging.Default()
|
logger := logging.Default()
|
||||||
|
|
||||||
|
// Connect to PostgreSQL
|
||||||
|
dbCfg := config.ReadDatabaseConfig()
|
||||||
|
pool := database.MustConnect(context.Background(), dbCfg.URL, database.Options{
|
||||||
|
MaxOpenConns: dbCfg.MaxOpenConns,
|
||||||
|
MaxIdleConns: dbCfg.MaxIdleConns,
|
||||||
|
ConnMaxLifetime: dbCfg.ConnMaxLifetime,
|
||||||
|
})
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
// Run migrations
|
||||||
|
database.MustRunMigrations(context.Background(), pool, migrationsFS, "migrations")
|
||||||
|
|
||||||
// Create adapters (repositories)
|
// Create adapters (repositories)
|
||||||
exampleRepo := memory.NewExampleRepository()
|
prefRepo := postgres.NewPreferenceRepository(pool.DB)
|
||||||
|
|
||||||
// Create services (business logic)
|
// Create services (business logic)
|
||||||
exampleService := service.NewExampleService(exampleRepo, logger)
|
prefService := service.NewPreferenceService(prefRepo, logger)
|
||||||
|
|
||||||
// Create application
|
// Create application
|
||||||
application := app.New("preferences-api", app.WithDefaultPort(8001))
|
application := app.New("preferences-api", app.WithDefaultPort(8001))
|
||||||
|
|
||||||
// Register routes with dependency injection
|
// Register routes with dependency injection
|
||||||
api.RegisterRoutes(application, exampleService)
|
api.RegisterRoutes(application, prefService)
|
||||||
|
|
||||||
// Start server
|
// Start server
|
||||||
application.Run()
|
application.Run()
|
||||||
|
|||||||
@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS preferences (
|
||||||
|
user_id UUID PRIMARY KEY,
|
||||||
|
preferences JSONB NOT NULL DEFAULT '{}',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_preferences_updated_at ON preferences (updated_at);
|
||||||
@ -1,8 +1,12 @@
|
|||||||
module git.threesix.ai/jordan/slack5-1770606136/services/preferences-api
|
module git.threesix.ai/jordan/slack5-1770606136/services/preferences-api
|
||||||
|
|
||||||
go 1.23
|
go 1.24.0
|
||||||
|
|
||||||
|
toolchain go1.24.13
|
||||||
|
|
||||||
require git.threesix.ai/jordan/slack5-1770606136/pkg v0.0.0
|
require git.threesix.ai/jordan/slack5-1770606136/pkg v0.0.0
|
||||||
|
|
||||||
|
require golang.org/x/text v0.33.0 // indirect
|
||||||
|
|
||||||
// Use local workspace modules (for Docker builds without go.work)
|
// Use local workspace modules (for Docker builds without go.work)
|
||||||
replace git.threesix.ai/jordan/slack5-1770606136/pkg => ../../pkg
|
replace git.threesix.ai/jordan/slack5-1770606136/pkg => ../../pkg
|
||||||
|
|||||||
@ -0,0 +1,2 @@
|
|||||||
|
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||||
|
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||||
@ -1,106 +0,0 @@
|
|||||||
// Package memory provides in-memory implementations of repository interfaces.
|
|
||||||
// Useful for development, testing, and prototyping.
|
|
||||||
package memory
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Compile-time verification that ExampleRepository implements port.ExampleRepository.
|
|
||||||
var _ port.ExampleRepository = (*ExampleRepository)(nil)
|
|
||||||
|
|
||||||
// ExampleRepository is a thread-safe in-memory implementation of port.ExampleRepository.
|
|
||||||
type ExampleRepository struct {
|
|
||||||
mu sync.RWMutex
|
|
||||||
examples map[domain.ExampleID]*domain.Example
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewExampleRepository creates a new in-memory example repository.
|
|
||||||
func NewExampleRepository() *ExampleRepository {
|
|
||||||
return &ExampleRepository{
|
|
||||||
examples: make(map[domain.ExampleID]*domain.Example),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// List returns all examples.
|
|
||||||
func (r *ExampleRepository) List(ctx context.Context) ([]domain.Example, error) {
|
|
||||||
r.mu.RLock()
|
|
||||||
defer r.mu.RUnlock()
|
|
||||||
|
|
||||||
result := make([]domain.Example, 0, len(r.examples))
|
|
||||||
for _, e := range r.examples {
|
|
||||||
result = append(result, *e)
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns an example by ID.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
func (r *ExampleRepository) Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) {
|
|
||||||
r.mu.RLock()
|
|
||||||
defer r.mu.RUnlock()
|
|
||||||
|
|
||||||
e, ok := r.examples[id]
|
|
||||||
if !ok {
|
|
||||||
return nil, domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
// Return a copy to prevent external mutation
|
|
||||||
copy := *e
|
|
||||||
return ©, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create stores a new example.
|
|
||||||
func (r *ExampleRepository) Create(ctx context.Context, example *domain.Example) error {
|
|
||||||
r.mu.Lock()
|
|
||||||
defer r.mu.Unlock()
|
|
||||||
|
|
||||||
// Store a copy to prevent external mutation
|
|
||||||
copy := *example
|
|
||||||
r.examples[example.ID] = ©
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update modifies an existing example.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
func (r *ExampleRepository) Update(ctx context.Context, example *domain.Example) error {
|
|
||||||
r.mu.Lock()
|
|
||||||
defer r.mu.Unlock()
|
|
||||||
|
|
||||||
if _, ok := r.examples[example.ID]; !ok {
|
|
||||||
return domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
// Store a copy to prevent external mutation
|
|
||||||
copy := *example
|
|
||||||
r.examples[example.ID] = ©
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete removes an example by ID.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
func (r *ExampleRepository) Delete(ctx context.Context, id domain.ExampleID) error {
|
|
||||||
r.mu.Lock()
|
|
||||||
defer r.mu.Unlock()
|
|
||||||
|
|
||||||
if _, ok := r.examples[id]; !ok {
|
|
||||||
return domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
delete(r.examples, id)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExistsByName checks if an example with the given name exists.
|
|
||||||
func (r *ExampleRepository) ExistsByName(ctx context.Context, name string) (bool, error) {
|
|
||||||
r.mu.RLock()
|
|
||||||
defer r.mu.RUnlock()
|
|
||||||
|
|
||||||
for _, e := range r.examples {
|
|
||||||
if e.Name == name {
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
@ -0,0 +1,80 @@
|
|||||||
|
package postgres
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jmoiron/sqlx"
|
||||||
|
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PreferenceRepository implements port.PreferenceRepository using PostgreSQL.
|
||||||
|
type PreferenceRepository struct {
|
||||||
|
db *sqlx.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compile-time interface verification.
|
||||||
|
var _ port.PreferenceRepository = (*PreferenceRepository)(nil)
|
||||||
|
|
||||||
|
// NewPreferenceRepository creates a new PostgreSQL preference repository.
|
||||||
|
func NewPreferenceRepository(db *sqlx.DB) *PreferenceRepository {
|
||||||
|
return &PreferenceRepository{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
// preferenceRow represents a database row from the preferences table.
|
||||||
|
type preferenceRow struct {
|
||||||
|
UserID string `db:"user_id"`
|
||||||
|
Preferences []byte `db:"preferences"`
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
|
UpdatedAt time.Time `db:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns preferences for a user.
|
||||||
|
// Returns nil, nil when no row exists.
|
||||||
|
func (r *PreferenceRepository) Get(ctx context.Context, userID string) (*domain.UserPreferences, error) {
|
||||||
|
var row preferenceRow
|
||||||
|
err := r.db.GetContext(ctx, &row,
|
||||||
|
`SELECT user_id, preferences, created_at, updated_at FROM preferences WHERE user_id = $1`,
|
||||||
|
userID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
prefs := make(map[string]any)
|
||||||
|
if err := json.Unmarshal(row.Preferences, &prefs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &domain.UserPreferences{
|
||||||
|
UserID: row.UserID,
|
||||||
|
Preferences: prefs,
|
||||||
|
CreatedAt: row.CreatedAt,
|
||||||
|
UpdatedAt: row.UpdatedAt,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upsert creates or updates preferences for a user.
|
||||||
|
func (r *PreferenceRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error {
|
||||||
|
prefsJSON, err := json.Marshal(prefs.Preferences)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = r.db.ExecContext(ctx,
|
||||||
|
`INSERT INTO preferences (user_id, preferences, updated_at)
|
||||||
|
VALUES ($1, $2, NOW())
|
||||||
|
ON CONFLICT (user_id) DO UPDATE
|
||||||
|
SET preferences = $2, updated_at = NOW()`,
|
||||||
|
prefs.UserID, prefsJSON,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@ -1,170 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/app"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/httperror"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/httpresponse"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Example handles HTTP requests for example resources.
|
|
||||||
type Example struct {
|
|
||||||
svc *service.ExampleService
|
|
||||||
logger *logging.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewExample creates a new Example handler with injected dependencies.
|
|
||||||
func NewExample(svc *service.ExampleService, logger *logging.Logger) *Example {
|
|
||||||
return &Example{
|
|
||||||
svc: svc,
|
|
||||||
logger: logger.WithComponent("ExampleHandler"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateRequest is the request body for creating an example.
|
|
||||||
type CreateRequest struct {
|
|
||||||
Name string `json:"name" validate:"required,min=1,max=100"`
|
|
||||||
Description string `json:"description" validate:"max=500"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateRequest is the request body for updating an example.
|
|
||||||
type UpdateRequest struct {
|
|
||||||
Name string `json:"name" validate:"required,min=1,max=100"`
|
|
||||||
Description string `json:"description" validate:"max=500"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExampleResponse is the response for an example resource.
|
|
||||||
type ExampleResponse struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
CreatedAt string `json:"created_at"`
|
|
||||||
UpdatedAt string `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// toResponse converts a domain example to an API response.
|
|
||||||
func toResponse(e *domain.Example) ExampleResponse {
|
|
||||||
return ExampleResponse{
|
|
||||||
ID: e.ID.String(),
|
|
||||||
Name: e.Name,
|
|
||||||
Description: e.Description,
|
|
||||||
CreatedAt: e.CreatedAt.Format("2006-01-02T15:04:05Z"),
|
|
||||||
UpdatedAt: e.UpdatedAt.Format("2006-01-02T15:04:05Z"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// List returns all examples.
|
|
||||||
func (h *Example) List(w http.ResponseWriter, r *http.Request) error {
|
|
||||||
examples, err := h.svc.List(r.Context())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]ExampleResponse, len(examples))
|
|
||||||
for i, e := range examples {
|
|
||||||
result[i] = toResponse(&e)
|
|
||||||
}
|
|
||||||
|
|
||||||
httpresponse.OK(w, r, result)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns an example by ID.
|
|
||||||
func (h *Example) Get(w http.ResponseWriter, r *http.Request) error {
|
|
||||||
id := chi.URLParam(r, "id")
|
|
||||||
|
|
||||||
// Validate UUID format
|
|
||||||
if _, err := uuid.Parse(id); err != nil {
|
|
||||||
return httperror.BadRequest("invalid id format")
|
|
||||||
}
|
|
||||||
|
|
||||||
example, err := h.svc.Get(r.Context(), domain.ExampleID(id))
|
|
||||||
if err != nil {
|
|
||||||
return mapDomainError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
httpresponse.OK(w, r, toResponse(example))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create creates a new example.
|
|
||||||
func (h *Example) Create(w http.ResponseWriter, r *http.Request) error {
|
|
||||||
var req CreateRequest
|
|
||||||
if err := app.BindAndValidate(r, &req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
example, err := h.svc.Create(r.Context(), service.CreateInput{
|
|
||||||
Name: req.Name,
|
|
||||||
Description: req.Description,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return mapDomainError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
httpresponse.Created(w, r, toResponse(example))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update updates an existing example.
|
|
||||||
func (h *Example) Update(w http.ResponseWriter, r *http.Request) error {
|
|
||||||
id := chi.URLParam(r, "id")
|
|
||||||
|
|
||||||
if _, err := uuid.Parse(id); err != nil {
|
|
||||||
return httperror.BadRequest("invalid id format")
|
|
||||||
}
|
|
||||||
|
|
||||||
var req UpdateRequest
|
|
||||||
if err := app.BindAndValidate(r, &req); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
example, err := h.svc.Update(r.Context(), domain.ExampleID(id), service.UpdateInput{
|
|
||||||
Name: req.Name,
|
|
||||||
Description: req.Description,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return mapDomainError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
httpresponse.OK(w, r, toResponse(example))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete removes an example by ID.
|
|
||||||
func (h *Example) Delete(w http.ResponseWriter, r *http.Request) error {
|
|
||||||
id := chi.URLParam(r, "id")
|
|
||||||
|
|
||||||
if _, err := uuid.Parse(id); err != nil {
|
|
||||||
return httperror.BadRequest("invalid id format")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.svc.Delete(r.Context(), domain.ExampleID(id)); err != nil {
|
|
||||||
return mapDomainError(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
httpresponse.NoContent(w)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// mapDomainError converts domain errors to HTTP errors.
|
|
||||||
func mapDomainError(err error) error {
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, domain.ErrExampleNotFound):
|
|
||||||
return httperror.NotFound("example not found")
|
|
||||||
case errors.Is(err, domain.ErrDuplicateExample):
|
|
||||||
return httperror.Conflict("example with this name already exists")
|
|
||||||
case errors.Is(err, domain.ErrInvalidExampleName):
|
|
||||||
return httperror.BadRequest("invalid example name")
|
|
||||||
default:
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,402 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service"
|
|
||||||
)
|
|
||||||
|
|
||||||
// mockExampleRepository implements port.ExampleRepository for testing.
|
|
||||||
type mockExampleRepository struct {
|
|
||||||
mu sync.RWMutex
|
|
||||||
examples map[domain.ExampleID]*domain.Example
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ port.ExampleRepository = (*mockExampleRepository)(nil)
|
|
||||||
|
|
||||||
func newMockExampleRepository() *mockExampleRepository {
|
|
||||||
return &mockExampleRepository{
|
|
||||||
examples: make(map[domain.ExampleID]*domain.Example),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) List(ctx context.Context) ([]domain.Example, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
result := make([]domain.Example, 0, len(m.examples))
|
|
||||||
for _, e := range m.examples {
|
|
||||||
result = append(result, *e)
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
e, ok := m.examples[id]
|
|
||||||
if !ok {
|
|
||||||
return nil, domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
copy := *e
|
|
||||||
return ©, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) Create(ctx context.Context, example *domain.Example) error {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
copy := *example
|
|
||||||
m.examples[example.ID] = ©
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) Update(ctx context.Context, example *domain.Example) error {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
if _, ok := m.examples[example.ID]; !ok {
|
|
||||||
return domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
copy := *example
|
|
||||||
m.examples[example.ID] = ©
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) Delete(ctx context.Context, id domain.ExampleID) error {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
if _, ok := m.examples[id]; !ok {
|
|
||||||
return domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
delete(m.examples, id)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) ExistsByName(ctx context.Context, name string) (bool, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
for _, e := range m.examples {
|
|
||||||
if e.Name == name {
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTestHandler() (*Example, *mockExampleRepository) {
|
|
||||||
repo := newMockExampleRepository()
|
|
||||||
svc := service.NewExampleService(repo, logging.Nop())
|
|
||||||
handler := NewExample(svc, logging.Nop())
|
|
||||||
return handler, repo
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExample_List(t *testing.T) {
|
|
||||||
handler, repo := newTestHandler()
|
|
||||||
|
|
||||||
// Seed data
|
|
||||||
ex, _ := domain.NewExample("test-id-1", "Test Example", "Description")
|
|
||||||
_ = repo.Create(context.Background(), ex)
|
|
||||||
|
|
||||||
r := chi.NewRouter()
|
|
||||||
r.Get("/api/v1/examples", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if err := handler.List(w, r); err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/examples", nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("expected status 200, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
var resp map[string]any
|
|
||||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
|
||||||
t.Fatalf("failed to decode response: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
data, ok := resp["data"]
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("expected 'data' field in response")
|
|
||||||
}
|
|
||||||
|
|
||||||
items, ok := data.([]any)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("expected 'data' to be an array")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(items) != 1 {
|
|
||||||
t.Errorf("expected 1 item, got %d", len(items))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExample_Get(t *testing.T) {
|
|
||||||
handler, repo := newTestHandler()
|
|
||||||
|
|
||||||
// Seed data
|
|
||||||
ex, _ := domain.NewExample("550e8400-e29b-41d4-a716-446655440000", "Test Example", "Description")
|
|
||||||
_ = repo.Create(context.Background(), ex)
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
id string
|
|
||||||
wantStatus int
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "valid uuid - found",
|
|
||||||
id: "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
wantStatus: http.StatusOK,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "valid uuid - not found",
|
|
||||||
id: "550e8400-e29b-41d4-a716-446655440001",
|
|
||||||
wantStatus: http.StatusNotFound,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "invalid uuid",
|
|
||||||
id: "not-a-uuid",
|
|
||||||
wantStatus: http.StatusBadRequest,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
r := chi.NewRouter()
|
|
||||||
r.Get("/api/v1/examples/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if err := handler.Get(w, r); err != nil {
|
|
||||||
// Map error to status for testing
|
|
||||||
switch tt.wantStatus {
|
|
||||||
case http.StatusNotFound:
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
case http.StatusBadRequest:
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
default:
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/examples/"+tt.id, nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != tt.wantStatus {
|
|
||||||
t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExample_Create(t *testing.T) {
|
|
||||||
handler, repo := newTestHandler()
|
|
||||||
|
|
||||||
// Seed existing data for duplicate test
|
|
||||||
ex, _ := domain.NewExample("existing-id", "Existing Name", "")
|
|
||||||
_ = repo.Create(context.Background(), ex)
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
body any
|
|
||||||
wantStatus int
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "valid request",
|
|
||||||
body: CreateRequest{
|
|
||||||
Name: "New Example",
|
|
||||||
Description: "A test description",
|
|
||||||
},
|
|
||||||
wantStatus: http.StatusCreated,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "empty body",
|
|
||||||
body: nil,
|
|
||||||
wantStatus: http.StatusBadRequest,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "duplicate name",
|
|
||||||
body: CreateRequest{
|
|
||||||
Name: "Existing Name",
|
|
||||||
Description: "Conflict",
|
|
||||||
},
|
|
||||||
wantStatus: http.StatusConflict,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
r := chi.NewRouter()
|
|
||||||
r.Post("/api/v1/examples", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if err := handler.Create(w, r); err != nil {
|
|
||||||
switch tt.wantStatus {
|
|
||||||
case http.StatusBadRequest:
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
case http.StatusConflict:
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
default:
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
var body []byte
|
|
||||||
if tt.body != nil {
|
|
||||||
var err error
|
|
||||||
body, err = json.Marshal(tt.body)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to marshal body: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/examples", bytes.NewReader(body))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != tt.wantStatus {
|
|
||||||
t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExample_Delete(t *testing.T) {
|
|
||||||
handler, repo := newTestHandler()
|
|
||||||
|
|
||||||
// Seed data
|
|
||||||
ex, _ := domain.NewExample("550e8400-e29b-41d4-a716-446655440000", "To Delete", "")
|
|
||||||
_ = repo.Create(context.Background(), ex)
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
id string
|
|
||||||
wantStatus int
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "existing example",
|
|
||||||
id: "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
wantStatus: http.StatusNoContent,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "non-existent example",
|
|
||||||
id: "550e8400-e29b-41d4-a716-446655440001",
|
|
||||||
wantStatus: http.StatusNotFound,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
r := chi.NewRouter()
|
|
||||||
r.Delete("/api/v1/examples/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if err := handler.Delete(w, r); err != nil {
|
|
||||||
if tt.wantStatus == http.StatusNotFound {
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
} else {
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/examples/"+tt.id, nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != tt.wantStatus {
|
|
||||||
t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExample_Update(t *testing.T) {
|
|
||||||
handler, repo := newTestHandler()
|
|
||||||
|
|
||||||
// Seed data
|
|
||||||
ex1, _ := domain.NewExample("550e8400-e29b-41d4-a716-446655440000", "Example 1", "")
|
|
||||||
_ = repo.Create(context.Background(), ex1)
|
|
||||||
ex2, _ := domain.NewExample("550e8400-e29b-41d4-a716-446655440001", "Example 2", "")
|
|
||||||
_ = repo.Create(context.Background(), ex2)
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
id string
|
|
||||||
body UpdateRequest
|
|
||||||
wantStatus int
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "valid update",
|
|
||||||
id: "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
body: UpdateRequest{
|
|
||||||
Name: "Updated Name",
|
|
||||||
Description: "Updated",
|
|
||||||
},
|
|
||||||
wantStatus: http.StatusOK,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "name conflict",
|
|
||||||
id: "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
body: UpdateRequest{
|
|
||||||
Name: "Example 2",
|
|
||||||
Description: "Conflict",
|
|
||||||
},
|
|
||||||
wantStatus: http.StatusConflict,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "not found",
|
|
||||||
id: "550e8400-e29b-41d4-a716-446655440099",
|
|
||||||
body: UpdateRequest{
|
|
||||||
Name: "Whatever",
|
|
||||||
Description: "",
|
|
||||||
},
|
|
||||||
wantStatus: http.StatusNotFound,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
r := chi.NewRouter()
|
|
||||||
r.Put("/api/v1/examples/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if err := handler.Update(w, r); err != nil {
|
|
||||||
switch tt.wantStatus {
|
|
||||||
case http.StatusNotFound:
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
case http.StatusConflict:
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
default:
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
body, _ := json.Marshal(tt.body)
|
|
||||||
req := httptest.NewRequest(http.MethodPut, "/api/v1/examples/"+tt.id, bytes.NewReader(body))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w, req)
|
|
||||||
|
|
||||||
if w.Code != tt.wantStatus {
|
|
||||||
t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
122
services/preferences-api/internal/api/handlers/preference.go
Normal file
122
services/preferences-api/internal/api/handlers/preference.go
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/app"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/httperror"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/httpresponse"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Preference handles HTTP requests for user preference resources.
|
||||||
|
type Preference struct {
|
||||||
|
svc *service.PreferenceService
|
||||||
|
logger *logging.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPreference creates a new Preference handler with injected dependencies.
|
||||||
|
func NewPreference(svc *service.PreferenceService, logger *logging.Logger) *Preference {
|
||||||
|
return &Preference{
|
||||||
|
svc: svc,
|
||||||
|
logger: logger.WithComponent("PreferenceHandler"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdatePreferencesRequest is the request body for updating preferences.
|
||||||
|
type UpdatePreferencesRequest struct {
|
||||||
|
Preferences map[string]any `json:"preferences"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PreferenceResponse is the response for a preference resource.
|
||||||
|
type PreferenceResponse struct {
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
Preferences map[string]any `json:"preferences"`
|
||||||
|
UpdatedAt string `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns preferences for a user.
|
||||||
|
func (h *Preference) Get(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
userID := chi.URLParam(r, "user_id")
|
||||||
|
|
||||||
|
if _, err := uuid.Parse(userID); err != nil {
|
||||||
|
return httperror.BadRequest("invalid user_id format")
|
||||||
|
}
|
||||||
|
|
||||||
|
prefs, err := h.svc.Get(r.Context(), userID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if prefs == nil {
|
||||||
|
httpresponse.OK(w, r, PreferenceResponse{
|
||||||
|
UserID: userID,
|
||||||
|
Preferences: map[string]any{},
|
||||||
|
UpdatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
httpresponse.OK(w, r, toPreferenceResponse(prefs))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upsert creates or updates preferences for a user.
|
||||||
|
func (h *Preference) Upsert(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
userID := chi.URLParam(r, "user_id")
|
||||||
|
|
||||||
|
if _, err := uuid.Parse(userID); err != nil {
|
||||||
|
return httperror.BadRequest("invalid user_id format")
|
||||||
|
}
|
||||||
|
|
||||||
|
var req UpdatePreferencesRequest
|
||||||
|
if err := app.Bind(r, &req); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Preferences == nil {
|
||||||
|
return httperror.BadRequest("preferences field is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := h.svc.Upsert(r.Context(), service.UpsertInput{
|
||||||
|
UserID: userID,
|
||||||
|
Preferences: req.Preferences,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return mapPreferenceDomainError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpresponse.OK(w, r, toPreferenceResponse(result))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// toPreferenceResponse converts a domain UserPreferences to an API response.
|
||||||
|
func toPreferenceResponse(p *domain.UserPreferences) PreferenceResponse {
|
||||||
|
return PreferenceResponse{
|
||||||
|
UserID: p.UserID,
|
||||||
|
Preferences: p.Preferences,
|
||||||
|
UpdatedAt: p.UpdatedAt.Format(time.RFC3339),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// mapPreferenceDomainError converts domain errors to HTTP errors.
|
||||||
|
func mapPreferenceDomainError(err error) error {
|
||||||
|
if errors.Is(err, domain.ErrInvalidPreferenceValue) {
|
||||||
|
var valErr *service.ValidationError
|
||||||
|
if errors.As(err, &valErr) {
|
||||||
|
return httperror.WithDetails(
|
||||||
|
httperror.Validation("Invalid preference values"),
|
||||||
|
valErr.Details,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return httperror.BadRequest("invalid preference value")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
@ -0,0 +1,272 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/httperror"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mockPreferenceRepository implements port.PreferenceRepository for handler testing.
|
||||||
|
type mockPreferenceRepository struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
prefs map[string]*domain.UserPreferences
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ port.PreferenceRepository = (*mockPreferenceRepository)(nil)
|
||||||
|
|
||||||
|
func newMockPrefRepository() *mockPreferenceRepository {
|
||||||
|
return &mockPreferenceRepository{
|
||||||
|
prefs: make(map[string]*domain.UserPreferences),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockPreferenceRepository) Get(ctx context.Context, userID string) (*domain.UserPreferences, error) {
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
|
||||||
|
p, ok := m.prefs[userID]
|
||||||
|
if !ok {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
cp := *p
|
||||||
|
cpPrefs := make(map[string]any)
|
||||||
|
for k, v := range p.Preferences {
|
||||||
|
cpPrefs[k] = v
|
||||||
|
}
|
||||||
|
cp.Preferences = cpPrefs
|
||||||
|
return &cp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockPreferenceRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
cp := *prefs
|
||||||
|
cpPrefs := make(map[string]any)
|
||||||
|
for k, v := range prefs.Preferences {
|
||||||
|
cpPrefs[k] = v
|
||||||
|
}
|
||||||
|
cp.Preferences = cpPrefs
|
||||||
|
m.prefs[prefs.UserID] = &cp
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestPreferenceHandler() (*Preference, *mockPreferenceRepository) {
|
||||||
|
repo := newMockPrefRepository()
|
||||||
|
svc := service.NewPreferenceService(repo, logging.Nop())
|
||||||
|
handler := NewPreference(svc, logging.Nop())
|
||||||
|
return handler, repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreference_Get(t *testing.T) {
|
||||||
|
handler, repo := newTestPreferenceHandler()
|
||||||
|
|
||||||
|
// Seed data
|
||||||
|
repo.prefs["550e8400-e29b-41d4-a716-446655440000"] = &domain.UserPreferences{
|
||||||
|
UserID: "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
Preferences: map[string]any{"theme": "dark"},
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
userID string
|
||||||
|
wantStatus int
|
||||||
|
checkBody func(t *testing.T, body map[string]any)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "returns existing preferences",
|
||||||
|
userID: "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
wantStatus: http.StatusOK,
|
||||||
|
checkBody: func(t *testing.T, body map[string]any) {
|
||||||
|
data, ok := body["data"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("expected 'data' field in response")
|
||||||
|
}
|
||||||
|
prefs, ok := data["preferences"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("expected 'preferences' field in data")
|
||||||
|
}
|
||||||
|
if prefs["theme"] != "dark" {
|
||||||
|
t.Errorf("expected theme 'dark', got '%v'", prefs["theme"])
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "returns empty preferences for unknown user",
|
||||||
|
userID: "550e8400-e29b-41d4-a716-446655440001",
|
||||||
|
wantStatus: http.StatusOK,
|
||||||
|
checkBody: func(t *testing.T, body map[string]any) {
|
||||||
|
data, ok := body["data"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("expected 'data' field in response")
|
||||||
|
}
|
||||||
|
prefs, ok := data["preferences"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("expected 'preferences' field in data")
|
||||||
|
}
|
||||||
|
if len(prefs) != 0 {
|
||||||
|
t.Errorf("expected empty preferences, got %v", prefs)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "returns 400 for invalid UUID",
|
||||||
|
userID: "not-a-uuid",
|
||||||
|
wantStatus: http.StatusBadRequest,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Get("/preferences/{user_id}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if err := handler.Get(w, r); err != nil {
|
||||||
|
// Write error status for test verification
|
||||||
|
httpErr, ok := err.(*httperror.HTTPError)
|
||||||
|
if ok {
|
||||||
|
w.WriteHeader(httpErr.Status)
|
||||||
|
} else {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/preferences/"+tt.userID, nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != tt.wantStatus {
|
||||||
|
t.Errorf("expected status %d, got %d", tt.wantStatus, w.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tt.checkBody != nil && w.Code == http.StatusOK {
|
||||||
|
var body map[string]any
|
||||||
|
if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
|
||||||
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
|
}
|
||||||
|
tt.checkBody(t, body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreference_Upsert(t *testing.T) {
|
||||||
|
handler, _ := newTestPreferenceHandler()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
userID string
|
||||||
|
body any
|
||||||
|
wantStatus int
|
||||||
|
checkBody func(t *testing.T, body map[string]any)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "creates preferences successfully",
|
||||||
|
userID: "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
body: UpdatePreferencesRequest{
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"theme": "dark",
|
||||||
|
"language": "en",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantStatus: http.StatusOK,
|
||||||
|
checkBody: func(t *testing.T, body map[string]any) {
|
||||||
|
data, ok := body["data"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("expected 'data' field in response")
|
||||||
|
}
|
||||||
|
prefs := data["preferences"].(map[string]any)
|
||||||
|
if prefs["theme"] != "dark" {
|
||||||
|
t.Errorf("expected theme 'dark', got '%v'", prefs["theme"])
|
||||||
|
}
|
||||||
|
if data["user_id"] != "550e8400-e29b-41d4-a716-446655440000" {
|
||||||
|
t.Errorf("expected user_id in response, got '%v'", data["user_id"])
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "returns 400 for invalid theme",
|
||||||
|
userID: "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
body: UpdatePreferencesRequest{
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"theme": "neon",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
wantStatus: http.StatusBadRequest,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "returns 400 for missing preferences field",
|
||||||
|
userID: "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
body: map[string]any{},
|
||||||
|
wantStatus: http.StatusBadRequest,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "returns 400 for invalid UUID",
|
||||||
|
userID: "not-a-uuid",
|
||||||
|
body: UpdatePreferencesRequest{Preferences: map[string]any{"theme": "dark"}},
|
||||||
|
wantStatus: http.StatusBadRequest,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "returns 400 for empty body",
|
||||||
|
userID: "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
body: nil,
|
||||||
|
wantStatus: http.StatusBadRequest,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Put("/preferences/{user_id}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if err := handler.Upsert(w, r); err != nil {
|
||||||
|
httpErr, ok := err.(*httperror.HTTPError)
|
||||||
|
if ok {
|
||||||
|
w.WriteHeader(httpErr.Status)
|
||||||
|
} else {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
var bodyBytes []byte
|
||||||
|
if tt.body != nil {
|
||||||
|
var err error
|
||||||
|
bodyBytes, err = json.Marshal(tt.body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to marshal body: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPut, "/preferences/"+tt.userID, bytes.NewReader(bodyBytes))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != tt.wantStatus {
|
||||||
|
t.Errorf("expected status %d, got %d (body: %s)", tt.wantStatus, w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
if tt.checkBody != nil && w.Code == http.StatusOK {
|
||||||
|
var body map[string]any
|
||||||
|
if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
|
||||||
|
t.Fatalf("failed to decode response: %v", err)
|
||||||
|
}
|
||||||
|
tt.checkBody(t, body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,9 +3,7 @@ package api
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/app"
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/app"
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/auth"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/api/handlers"
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/api/handlers"
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/config"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service"
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -13,14 +11,13 @@ import (
|
|||||||
// Routes are mounted under /api/preferences-api to match the ingress path routing.
|
// Routes are mounted under /api/preferences-api to match the ingress path routing.
|
||||||
// This allows the monorepo to expose multiple services under a single domain:
|
// This allows the monorepo to expose multiple services under a single domain:
|
||||||
// - https://domain/api/preferences-api/health
|
// - https://domain/api/preferences-api/health
|
||||||
// - https://domain/api/preferences-api/examples
|
// - https://domain/api/preferences-api/preferences/{user_id}
|
||||||
func RegisterRoutes(application *app.App, exampleService *service.ExampleService) {
|
func RegisterRoutes(application *app.App, prefService *service.PreferenceService) {
|
||||||
logger := application.Logger()
|
logger := application.Logger()
|
||||||
cfg := config.Load()
|
|
||||||
|
|
||||||
// Initialize handlers with injected services
|
// Initialize handlers with injected services
|
||||||
healthHandler := handlers.NewHealth(logger)
|
healthHandler := handlers.NewHealth(logger)
|
||||||
exampleHandler := handlers.NewExample(exampleService, logger)
|
prefHandler := handlers.NewPreference(prefService, logger)
|
||||||
|
|
||||||
// Build and mount OpenAPI spec
|
// Build and mount OpenAPI spec
|
||||||
spec := NewServiceSpec()
|
spec := NewServiceSpec()
|
||||||
@ -31,24 +28,8 @@ func RegisterRoutes(application *app.App, exampleService *service.ExampleService
|
|||||||
application.Route("/api/preferences-api", func(r app.Router) {
|
application.Route("/api/preferences-api", func(r app.Router) {
|
||||||
r.Get("/health", healthHandler.Check)
|
r.Get("/health", healthHandler.Check)
|
||||||
|
|
||||||
// Public routes (no auth required)
|
// Preference routes (auth out of scope per spec; can be layered on later)
|
||||||
r.Get("/examples", app.Wrap(exampleHandler.List))
|
r.Get("/preferences/{user_id}", app.Wrap(prefHandler.Get))
|
||||||
r.Get("/examples/{id}", app.Wrap(exampleHandler.Get))
|
r.Put("/preferences/{user_id}", app.Wrap(prefHandler.Upsert))
|
||||||
|
|
||||||
// Protected routes (auth required when enabled)
|
|
||||||
r.Group(func(r app.Router) {
|
|
||||||
if cfg.AuthEnabled {
|
|
||||||
r.Use(auth.Middleware(auth.MiddlewareConfig{
|
|
||||||
Validator: auth.NewJWTValidator(auth.JWTConfig{
|
|
||||||
Secret: []byte(cfg.JWTSecret),
|
|
||||||
Issuer: "slack5-1770606136",
|
|
||||||
}),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Post("/examples", app.Wrap(exampleHandler.Create))
|
|
||||||
r.Put("/examples/{id}", app.Wrap(exampleHandler.Update))
|
|
||||||
r.Delete("/examples/{id}", app.Wrap(exampleHandler.Delete))
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,29 +5,20 @@ import "git.threesix.ai/jordan/slack5-1770606136/pkg/openapi"
|
|||||||
// NewServiceSpec builds the OpenAPI specification for the preferences-api service.
|
// NewServiceSpec builds the OpenAPI specification for the preferences-api service.
|
||||||
func NewServiceSpec() *openapi.OpenAPISpec {
|
func NewServiceSpec() *openapi.OpenAPISpec {
|
||||||
spec := openapi.NewOpenAPISpec("preferences-api API", "1.0.0").
|
spec := openapi.NewOpenAPISpec("preferences-api API", "1.0.0").
|
||||||
WithDescription("REST API for the preferences-api service").
|
WithDescription("REST API for the preferences-api service - manages user preferences").
|
||||||
WithBearerSecurity("bearer", "JWT authentication token").
|
|
||||||
WithTag("Health", "Service health endpoints").
|
WithTag("Health", "Service health endpoints").
|
||||||
WithTag("Examples", "Example CRUD endpoints")
|
WithTag("Preferences", "User preference endpoints")
|
||||||
|
|
||||||
// Define reusable schemas
|
// Define reusable schemas
|
||||||
spec.WithSchema("Example", openapi.Object(map[string]openapi.Schema{
|
spec.WithSchema("UserPreferences", openapi.Object(map[string]openapi.Schema{
|
||||||
"id": openapi.UUID().WithDescription("Unique identifier"),
|
"user_id": openapi.UUID().WithDescription("User identifier"),
|
||||||
"name": openapi.String().WithDescription("Name of the example").WithExample("My Example"),
|
"preferences": openapi.Object(map[string]openapi.Schema{}).WithDescription("Key-value preference pairs"),
|
||||||
"description": openapi.String().WithDescription("Optional description").WithExample("A description"),
|
|
||||||
"created_at": openapi.DateTime().WithDescription("Creation timestamp"),
|
|
||||||
"updated_at": openapi.DateTime().WithDescription("Last update timestamp"),
|
"updated_at": openapi.DateTime().WithDescription("Last update timestamp"),
|
||||||
}, "id", "name"))
|
}, "user_id", "preferences", "updated_at"))
|
||||||
|
|
||||||
spec.WithSchema("CreateExampleRequest", openapi.Object(map[string]openapi.Schema{
|
spec.WithSchema("UpdatePreferencesRequest", openapi.Object(map[string]openapi.Schema{
|
||||||
"name": openapi.StringWithMinMax(1, 100).WithDescription("Name of the example"),
|
"preferences": openapi.Object(map[string]openapi.Schema{}).WithDescription("Key-value preference pairs to set"),
|
||||||
"description": openapi.StringWithMinMax(0, 500).WithDescription("Optional description"),
|
}, "preferences"))
|
||||||
}, "name"))
|
|
||||||
|
|
||||||
spec.WithSchema("UpdateExampleRequest", openapi.Object(map[string]openapi.Schema{
|
|
||||||
"name": openapi.StringWithMinMax(1, 100).WithDescription("Updated name"),
|
|
||||||
"description": openapi.StringWithMinMax(0, 500).WithDescription("Updated description"),
|
|
||||||
}))
|
|
||||||
|
|
||||||
// Health
|
// Health
|
||||||
spec.AddPath("/api/preferences-api/health", "get", map[string]any{
|
spec.AddPath("/api/preferences-api/health", "get", map[string]any{
|
||||||
@ -41,70 +32,28 @@ func NewServiceSpec() *openapi.OpenAPISpec {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// List examples
|
// Get preferences
|
||||||
spec.AddPath("/api/preferences-api/examples", "get", map[string]any{
|
spec.AddPath("/api/preferences-api/preferences/{user_id}", "get", map[string]any{
|
||||||
"summary": "List examples",
|
"summary": "Get user preferences",
|
||||||
"description": "Returns a paginated list of examples.",
|
"description": "Returns all preferences for a user. Returns empty preferences object if user has none.",
|
||||||
"tags": []string{"Examples"},
|
"tags": []string{"Preferences"},
|
||||||
"parameters": []any{openapi.PageParam(), openapi.PerPageParam()},
|
"parameters": []any{openapi.PathParam("user_id", "User UUID")},
|
||||||
"responses": map[string]any{
|
"responses": map[string]any{
|
||||||
"200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.RefArray("Example"))),
|
"200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.Ref("UserPreferences"))),
|
||||||
|
"400": openapi.OpResponse("Invalid user_id format", openapi.ErrorResponseSchema()),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// Get example
|
// Update preferences
|
||||||
spec.AddPath("/api/preferences-api/examples/{id}", "get", map[string]any{
|
spec.AddPath("/api/preferences-api/preferences/{user_id}", "put", map[string]any{
|
||||||
"summary": "Get example by ID",
|
"summary": "Update user preferences",
|
||||||
"tags": []string{"Examples"},
|
"description": "Creates or updates preferences for a user. Merges with existing preferences.",
|
||||||
"parameters": []any{openapi.IDParam()},
|
"tags": []string{"Preferences"},
|
||||||
|
"parameters": []any{openapi.PathParam("user_id", "User UUID")},
|
||||||
|
"requestBody": openapi.RequestBody(openapi.Ref("UpdatePreferencesRequest"), true),
|
||||||
"responses": map[string]any{
|
"responses": map[string]any{
|
||||||
"200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.Ref("Example"))),
|
"200": openapi.OpResponse("Updated", openapi.ResponseSchema(openapi.Ref("UserPreferences"))),
|
||||||
"404": openapi.OpResponse("Not found", openapi.ErrorResponseSchema()),
|
"400": openapi.OpResponse("Validation error", openapi.ErrorResponseSchema()),
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// Create example
|
|
||||||
spec.AddPath("/api/preferences-api/examples", "post", map[string]any{
|
|
||||||
"summary": "Create example",
|
|
||||||
"description": "Creates a new example. Requires authentication.",
|
|
||||||
"tags": []string{"Examples"},
|
|
||||||
"security": []map[string][]string{{"bearer": {}}},
|
|
||||||
"requestBody": openapi.RequestBody(openapi.Ref("CreateExampleRequest"), true),
|
|
||||||
"responses": map[string]any{
|
|
||||||
"201": openapi.OpResponse("Created", openapi.ResponseSchema(openapi.Ref("Example"))),
|
|
||||||
"400": openapi.OpResponse("Bad request", openapi.ErrorResponseSchema()),
|
|
||||||
"401": openapi.OpResponse("Unauthorized", openapi.ErrorResponseSchema()),
|
|
||||||
"422": openapi.OpResponse("Validation error", openapi.ErrorResponseSchema()),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// Update example
|
|
||||||
spec.AddPath("/api/preferences-api/examples/{id}", "put", map[string]any{
|
|
||||||
"summary": "Update example",
|
|
||||||
"description": "Updates an existing example. Requires authentication.",
|
|
||||||
"tags": []string{"Examples"},
|
|
||||||
"security": []map[string][]string{{"bearer": {}}},
|
|
||||||
"parameters": []any{openapi.IDParam()},
|
|
||||||
"requestBody": openapi.RequestBody(openapi.Ref("UpdateExampleRequest"), true),
|
|
||||||
"responses": map[string]any{
|
|
||||||
"200": openapi.OpResponse("Updated", openapi.ResponseSchema(openapi.Ref("Example"))),
|
|
||||||
"400": openapi.OpResponse("Bad request", openapi.ErrorResponseSchema()),
|
|
||||||
"401": openapi.OpResponse("Unauthorized", openapi.ErrorResponseSchema()),
|
|
||||||
"404": openapi.OpResponse("Not found", openapi.ErrorResponseSchema()),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// Delete example
|
|
||||||
spec.AddPath("/api/preferences-api/examples/{id}", "delete", map[string]any{
|
|
||||||
"summary": "Delete example",
|
|
||||||
"description": "Deletes an example by ID. Requires authentication.",
|
|
||||||
"tags": []string{"Examples"},
|
|
||||||
"security": []map[string][]string{{"bearer": {}}},
|
|
||||||
"parameters": []any{openapi.IDParam()},
|
|
||||||
"responses": map[string]any{
|
|
||||||
"204": openapi.OpResponseNoContent(),
|
|
||||||
"401": openapi.OpResponse("Unauthorized", openapi.ErrorResponseSchema()),
|
|
||||||
"404": openapi.OpResponse("Not found", openapi.ErrorResponseSchema()),
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@ -7,15 +7,9 @@ import "errors"
|
|||||||
// Domain errors - these are business-level errors that should be translated
|
// Domain errors - these are business-level errors that should be translated
|
||||||
// to appropriate HTTP status codes by the handler layer.
|
// to appropriate HTTP status codes by the handler layer.
|
||||||
var (
|
var (
|
||||||
// ErrNotFound indicates a requested resource does not exist.
|
// ErrInvalidUserID indicates the user ID is invalid.
|
||||||
ErrNotFound = errors.New("not found")
|
ErrInvalidUserID = errors.New("invalid user ID")
|
||||||
|
|
||||||
// ErrExampleNotFound indicates the requested example does not exist.
|
// ErrInvalidPreferenceValue indicates one or more preference values are invalid.
|
||||||
ErrExampleNotFound = errors.New("example not found")
|
ErrInvalidPreferenceValue = errors.New("invalid preference value")
|
||||||
|
|
||||||
// ErrDuplicateExample indicates an example with the same name already exists.
|
|
||||||
ErrDuplicateExample = errors.New("example with this name already exists")
|
|
||||||
|
|
||||||
// ErrInvalidExampleName indicates the example name is invalid.
|
|
||||||
ErrInvalidExampleName = errors.New("invalid example name")
|
|
||||||
)
|
)
|
||||||
|
|||||||
@ -1,89 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
"unicode/utf8"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ExampleID is a strongly-typed identifier for examples.
|
|
||||||
type ExampleID string
|
|
||||||
|
|
||||||
// String returns the string representation of the ID.
|
|
||||||
func (id ExampleID) String() string {
|
|
||||||
return string(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsZero returns true if the ID is empty.
|
|
||||||
func (id ExampleID) IsZero() bool {
|
|
||||||
return id == ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// Example name constraints.
|
|
||||||
const (
|
|
||||||
MinExampleNameLen = 1
|
|
||||||
MaxExampleNameLen = 100
|
|
||||||
MaxDescriptionLen = 500
|
|
||||||
)
|
|
||||||
|
|
||||||
// Example represents an example domain entity.
|
|
||||||
// This is a pure domain model with no external dependencies.
|
|
||||||
type Example struct {
|
|
||||||
ID ExampleID
|
|
||||||
Name string
|
|
||||||
Description string
|
|
||||||
CreatedAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewExample creates a new Example with validation.
|
|
||||||
// Returns ErrInvalidExampleName if the name is invalid.
|
|
||||||
func NewExample(id ExampleID, name, description string) (*Example, error) {
|
|
||||||
if err := validateExampleName(name); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if err := validateDescription(description); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Now().UTC()
|
|
||||||
return &Example{
|
|
||||||
ID: id,
|
|
||||||
Name: name,
|
|
||||||
Description: description,
|
|
||||||
CreatedAt: now,
|
|
||||||
UpdatedAt: now,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update modifies the example's mutable fields with validation.
|
|
||||||
// Returns ErrInvalidExampleName if the name is invalid.
|
|
||||||
func (e *Example) Update(name, description string) error {
|
|
||||||
if err := validateExampleName(name); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := validateDescription(description); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
e.Name = name
|
|
||||||
e.Description = description
|
|
||||||
e.UpdatedAt = time.Now().UTC()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// validateExampleName validates an example name.
|
|
||||||
func validateExampleName(name string) error {
|
|
||||||
length := utf8.RuneCountInString(name)
|
|
||||||
if length < MinExampleNameLen || length > MaxExampleNameLen {
|
|
||||||
return ErrInvalidExampleName
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// validateDescription validates a description.
|
|
||||||
func validateDescription(desc string) error {
|
|
||||||
if utf8.RuneCountInString(desc) > MaxDescriptionLen {
|
|
||||||
return ErrInvalidExampleName
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
11
services/preferences-api/internal/domain/preference.go
Normal file
11
services/preferences-api/internal/domain/preference.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// UserPreferences represents a user's stored preferences.
|
||||||
|
type UserPreferences struct {
|
||||||
|
UserID string
|
||||||
|
Preferences map[string]any
|
||||||
|
CreatedAt time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
@ -1,37 +0,0 @@
|
|||||||
// Package port defines interfaces (ports) for external dependencies.
|
|
||||||
// These interfaces define the contracts between the application core and
|
|
||||||
// infrastructure adapters, enabling testability and flexibility.
|
|
||||||
package port
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ExampleRepository defines the interface for example persistence operations.
|
|
||||||
// Implementations may use databases, in-memory storage, or external services.
|
|
||||||
type ExampleRepository interface {
|
|
||||||
// List returns all examples.
|
|
||||||
List(ctx context.Context) ([]domain.Example, error)
|
|
||||||
|
|
||||||
// Get returns an example by ID.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error)
|
|
||||||
|
|
||||||
// Create stores a new example.
|
|
||||||
// The example must have a valid ID set.
|
|
||||||
Create(ctx context.Context, example *domain.Example) error
|
|
||||||
|
|
||||||
// Update modifies an existing example.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
Update(ctx context.Context, example *domain.Example) error
|
|
||||||
|
|
||||||
// Delete removes an example by ID.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
Delete(ctx context.Context, id domain.ExampleID) error
|
|
||||||
|
|
||||||
// ExistsByName checks if an example with the given name exists.
|
|
||||||
// Used for duplicate detection.
|
|
||||||
ExistsByName(ctx context.Context, name string) (bool, error)
|
|
||||||
}
|
|
||||||
18
services/preferences-api/internal/port/preference.go
Normal file
18
services/preferences-api/internal/port/preference.go
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package port
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PreferenceRepository defines the interface for preference persistence operations.
|
||||||
|
type PreferenceRepository interface {
|
||||||
|
// Get returns preferences for a user.
|
||||||
|
// Returns nil, nil when no row exists for the given userID.
|
||||||
|
Get(ctx context.Context, userID string) (*domain.UserPreferences, error)
|
||||||
|
|
||||||
|
// Upsert creates or updates preferences for a user.
|
||||||
|
// Uses ON CONFLICT to handle both insert and update atomically.
|
||||||
|
Upsert(ctx context.Context, prefs *domain.UserPreferences) error
|
||||||
|
}
|
||||||
@ -1,137 +0,0 @@
|
|||||||
// Package service provides business logic / use cases for the application.
|
|
||||||
// Services orchestrate domain operations using port interfaces.
|
|
||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ExampleService handles example-related business logic.
|
|
||||||
type ExampleService struct {
|
|
||||||
repo port.ExampleRepository
|
|
||||||
logger *logging.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewExampleService creates a new example service.
|
|
||||||
func NewExampleService(repo port.ExampleRepository, logger *logging.Logger) *ExampleService {
|
|
||||||
return &ExampleService{
|
|
||||||
repo: repo,
|
|
||||||
logger: logger.WithService("ExampleService"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// List returns all examples.
|
|
||||||
func (s *ExampleService) List(ctx context.Context) ([]domain.Example, error) {
|
|
||||||
return s.repo.List(ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns an example by ID.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
func (s *ExampleService) Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) {
|
|
||||||
return s.repo.Get(ctx, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateInput contains the data needed to create an example.
|
|
||||||
type CreateInput struct {
|
|
||||||
Name string
|
|
||||||
Description string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create creates a new example with duplicate detection.
|
|
||||||
// Returns domain.ErrDuplicateExample if name already exists.
|
|
||||||
// Returns domain.ErrInvalidExampleName if name is invalid.
|
|
||||||
func (s *ExampleService) Create(ctx context.Context, input CreateInput) (*domain.Example, error) {
|
|
||||||
// Check for duplicates
|
|
||||||
exists, err := s.repo.ExistsByName(ctx, input.Name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if exists {
|
|
||||||
return nil, domain.ErrDuplicateExample
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate new ID
|
|
||||||
id := domain.ExampleID(uuid.New().String())
|
|
||||||
|
|
||||||
// Create domain entity (validates name)
|
|
||||||
example, err := domain.NewExample(id, input.Name, input.Description)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Persist
|
|
||||||
if err := s.repo.Create(ctx, example); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
s.logger.Info("example created", "id", id, "name", input.Name)
|
|
||||||
return example, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateInput contains the data needed to update an example.
|
|
||||||
type UpdateInput struct {
|
|
||||||
Name string
|
|
||||||
Description string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update modifies an existing example.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
// Returns domain.ErrDuplicateExample if new name conflicts with another example.
|
|
||||||
// Returns domain.ErrInvalidExampleName if name is invalid.
|
|
||||||
func (s *ExampleService) Update(ctx context.Context, id domain.ExampleID, input UpdateInput) (*domain.Example, error) {
|
|
||||||
// Fetch existing
|
|
||||||
example, err := s.repo.Get(ctx, id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for name conflicts (only if name changed)
|
|
||||||
if example.Name != input.Name {
|
|
||||||
exists, err := s.repo.ExistsByName(ctx, input.Name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if exists {
|
|
||||||
return nil, domain.ErrDuplicateExample
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update domain entity (validates name)
|
|
||||||
if err := example.Update(input.Name, input.Description); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Persist
|
|
||||||
if err := s.repo.Update(ctx, example); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
s.logger.Info("example updated", "id", id, "name", input.Name)
|
|
||||||
return example, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete removes an example by ID.
|
|
||||||
// Returns domain.ErrExampleNotFound if not found.
|
|
||||||
func (s *ExampleService) Delete(ctx context.Context, id domain.ExampleID) error {
|
|
||||||
// Verify exists before delete
|
|
||||||
if _, err := s.repo.Get(ctx, id); err != nil {
|
|
||||||
if errors.Is(err, domain.ErrExampleNotFound) {
|
|
||||||
return domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.repo.Delete(ctx, id); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
s.logger.Info("example deleted", "id", id)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@ -1,282 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
|
||||||
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port"
|
|
||||||
)
|
|
||||||
|
|
||||||
// mockExampleRepository implements port.ExampleRepository for testing.
|
|
||||||
type mockExampleRepository struct {
|
|
||||||
mu sync.RWMutex
|
|
||||||
examples map[domain.ExampleID]*domain.Example
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ port.ExampleRepository = (*mockExampleRepository)(nil)
|
|
||||||
|
|
||||||
func newMockExampleRepository() *mockExampleRepository {
|
|
||||||
return &mockExampleRepository{
|
|
||||||
examples: make(map[domain.ExampleID]*domain.Example),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) List(ctx context.Context) ([]domain.Example, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
result := make([]domain.Example, 0, len(m.examples))
|
|
||||||
for _, e := range m.examples {
|
|
||||||
result = append(result, *e)
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) Get(ctx context.Context, id domain.ExampleID) (*domain.Example, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
e, ok := m.examples[id]
|
|
||||||
if !ok {
|
|
||||||
return nil, domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
// Return a copy to avoid mutation
|
|
||||||
copy := *e
|
|
||||||
return ©, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) Create(ctx context.Context, example *domain.Example) error {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
// Store a copy
|
|
||||||
copy := *example
|
|
||||||
m.examples[example.ID] = ©
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) Update(ctx context.Context, example *domain.Example) error {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
if _, ok := m.examples[example.ID]; !ok {
|
|
||||||
return domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
// Store a copy
|
|
||||||
copy := *example
|
|
||||||
m.examples[example.ID] = ©
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) Delete(ctx context.Context, id domain.ExampleID) error {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
if _, ok := m.examples[id]; !ok {
|
|
||||||
return domain.ErrExampleNotFound
|
|
||||||
}
|
|
||||||
delete(m.examples, id)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *mockExampleRepository) ExistsByName(ctx context.Context, name string) (bool, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
for _, e := range m.examples {
|
|
||||||
if e.Name == name {
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExampleService_Create(t *testing.T) {
|
|
||||||
repo := newMockExampleRepository()
|
|
||||||
svc := NewExampleService(repo, logging.Nop())
|
|
||||||
|
|
||||||
t.Run("creates example successfully", func(t *testing.T) {
|
|
||||||
example, err := svc.Create(context.Background(), CreateInput{
|
|
||||||
Name: "Test Example",
|
|
||||||
Description: "A test description",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if example.Name != "Test Example" {
|
|
||||||
t.Errorf("expected name 'Test Example', got '%s'", example.Name)
|
|
||||||
}
|
|
||||||
if example.ID.IsZero() {
|
|
||||||
t.Error("expected non-empty ID")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("rejects duplicate name", func(t *testing.T) {
|
|
||||||
_, err := svc.Create(context.Background(), CreateInput{
|
|
||||||
Name: "Test Example",
|
|
||||||
Description: "Another description",
|
|
||||||
})
|
|
||||||
if err != domain.ErrDuplicateExample {
|
|
||||||
t.Errorf("expected ErrDuplicateExample, got %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("rejects empty name", func(t *testing.T) {
|
|
||||||
_, err := svc.Create(context.Background(), CreateInput{
|
|
||||||
Name: "",
|
|
||||||
Description: "Description",
|
|
||||||
})
|
|
||||||
if err != domain.ErrInvalidExampleName {
|
|
||||||
t.Errorf("expected ErrInvalidExampleName, got %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExampleService_Get(t *testing.T) {
|
|
||||||
repo := newMockExampleRepository()
|
|
||||||
svc := NewExampleService(repo, logging.Nop())
|
|
||||||
|
|
||||||
// Create an example first
|
|
||||||
created, _ := svc.Create(context.Background(), CreateInput{
|
|
||||||
Name: "Get Test",
|
|
||||||
Description: "Description",
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("returns existing example", func(t *testing.T) {
|
|
||||||
example, err := svc.Get(context.Background(), created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if example.Name != "Get Test" {
|
|
||||||
t.Errorf("expected name 'Get Test', got '%s'", example.Name)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("returns not found for missing example", func(t *testing.T) {
|
|
||||||
_, err := svc.Get(context.Background(), "nonexistent-id")
|
|
||||||
if err != domain.ErrExampleNotFound {
|
|
||||||
t.Errorf("expected ErrExampleNotFound, got %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExampleService_Update(t *testing.T) {
|
|
||||||
repo := newMockExampleRepository()
|
|
||||||
svc := NewExampleService(repo, logging.Nop())
|
|
||||||
|
|
||||||
// Create examples
|
|
||||||
example1, _ := svc.Create(context.Background(), CreateInput{
|
|
||||||
Name: "Update Test 1",
|
|
||||||
Description: "Original",
|
|
||||||
})
|
|
||||||
_, _ = svc.Create(context.Background(), CreateInput{
|
|
||||||
Name: "Update Test 2",
|
|
||||||
Description: "Other",
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("updates example successfully", func(t *testing.T) {
|
|
||||||
updated, err := svc.Update(context.Background(), example1.ID, UpdateInput{
|
|
||||||
Name: "Updated Name",
|
|
||||||
Description: "Updated description",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if updated.Name != "Updated Name" {
|
|
||||||
t.Errorf("expected name 'Updated Name', got '%s'", updated.Name)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("allows same name on same example", func(t *testing.T) {
|
|
||||||
_, err := svc.Update(context.Background(), example1.ID, UpdateInput{
|
|
||||||
Name: "Updated Name",
|
|
||||||
Description: "Same name",
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("unexpected error updating with same name: %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("rejects name conflict", func(t *testing.T) {
|
|
||||||
_, err := svc.Update(context.Background(), example1.ID, UpdateInput{
|
|
||||||
Name: "Update Test 2",
|
|
||||||
Description: "Conflict",
|
|
||||||
})
|
|
||||||
if err != domain.ErrDuplicateExample {
|
|
||||||
t.Errorf("expected ErrDuplicateExample, got %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("returns not found for missing example", func(t *testing.T) {
|
|
||||||
_, err := svc.Update(context.Background(), "nonexistent-id", UpdateInput{
|
|
||||||
Name: "Anything",
|
|
||||||
Description: "",
|
|
||||||
})
|
|
||||||
if err != domain.ErrExampleNotFound {
|
|
||||||
t.Errorf("expected ErrExampleNotFound, got %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExampleService_Delete(t *testing.T) {
|
|
||||||
repo := newMockExampleRepository()
|
|
||||||
svc := NewExampleService(repo, logging.Nop())
|
|
||||||
|
|
||||||
// Create an example first
|
|
||||||
created, _ := svc.Create(context.Background(), CreateInput{
|
|
||||||
Name: "Delete Test",
|
|
||||||
Description: "To be deleted",
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("deletes example successfully", func(t *testing.T) {
|
|
||||||
err := svc.Delete(context.Background(), created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify deleted
|
|
||||||
_, err = svc.Get(context.Background(), created.ID)
|
|
||||||
if err != domain.ErrExampleNotFound {
|
|
||||||
t.Errorf("expected ErrExampleNotFound after delete, got %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("returns not found for missing example", func(t *testing.T) {
|
|
||||||
err := svc.Delete(context.Background(), "nonexistent-id")
|
|
||||||
if err != domain.ErrExampleNotFound {
|
|
||||||
t.Errorf("expected ErrExampleNotFound, got %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExampleService_List(t *testing.T) {
|
|
||||||
repo := newMockExampleRepository()
|
|
||||||
svc := NewExampleService(repo, logging.Nop())
|
|
||||||
|
|
||||||
t.Run("returns empty list initially", func(t *testing.T) {
|
|
||||||
examples, err := svc.List(context.Background())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if len(examples) != 0 {
|
|
||||||
t.Errorf("expected 0 examples, got %d", len(examples))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Create some examples
|
|
||||||
_, _ = svc.Create(context.Background(), CreateInput{Name: "List Test 1", Description: ""})
|
|
||||||
_, _ = svc.Create(context.Background(), CreateInput{Name: "List Test 2", Description: ""})
|
|
||||||
|
|
||||||
t.Run("returns all examples", func(t *testing.T) {
|
|
||||||
examples, err := svc.List(context.Background())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if len(examples) != 2 {
|
|
||||||
t.Errorf("expected 2 examples, got %d", len(examples))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
133
services/preferences-api/internal/service/preference.go
Normal file
133
services/preferences-api/internal/service/preference.go
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/text/language"
|
||||||
|
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ValidationError carries per-field validation details.
|
||||||
|
// It wraps domain.ErrInvalidPreferenceValue for errors.Is() matching.
|
||||||
|
type ValidationError struct {
|
||||||
|
Details map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ValidationError) Error() string { return "invalid preference values" }
|
||||||
|
func (e *ValidationError) Unwrap() error { return domain.ErrInvalidPreferenceValue }
|
||||||
|
|
||||||
|
// validThemes is the set of allowed values for the "theme" preference.
|
||||||
|
var validThemes = map[string]bool{
|
||||||
|
"light": true,
|
||||||
|
"dark": true,
|
||||||
|
"system": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// PreferenceService handles preference-related business logic.
|
||||||
|
type PreferenceService struct {
|
||||||
|
repo port.PreferenceRepository
|
||||||
|
logger *logging.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPreferenceService creates a new preference service.
|
||||||
|
func NewPreferenceService(repo port.PreferenceRepository, logger *logging.Logger) *PreferenceService {
|
||||||
|
return &PreferenceService{
|
||||||
|
repo: repo,
|
||||||
|
logger: logger.WithService("PreferenceService"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns preferences for a user.
|
||||||
|
// Returns nil when no preferences exist.
|
||||||
|
func (s *PreferenceService) Get(ctx context.Context, userID string) (*domain.UserPreferences, error) {
|
||||||
|
return s.repo.Get(ctx, userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpsertInput contains the data needed to upsert preferences.
|
||||||
|
type UpsertInput struct {
|
||||||
|
UserID string
|
||||||
|
Preferences map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upsert validates and stores preferences for a user.
|
||||||
|
// Known keys are validated; unknown keys are accepted as-is.
|
||||||
|
// Incoming keys are merged on top of existing preferences.
|
||||||
|
func (s *PreferenceService) Upsert(ctx context.Context, input UpsertInput) (*domain.UserPreferences, error) {
|
||||||
|
// Validate known preference keys
|
||||||
|
if err := validatePreferences(input.Preferences); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch existing preferences for merge
|
||||||
|
existing, err := s.repo.Get(ctx, input.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
merged := make(map[string]any)
|
||||||
|
if existing != nil {
|
||||||
|
for k, v := range existing.Preferences {
|
||||||
|
merged[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for k, v := range input.Preferences {
|
||||||
|
merged[k] = v
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UTC()
|
||||||
|
prefs := &domain.UserPreferences{
|
||||||
|
UserID: input.UserID,
|
||||||
|
Preferences: merged,
|
||||||
|
UpdatedAt: now,
|
||||||
|
}
|
||||||
|
if existing != nil {
|
||||||
|
prefs.CreatedAt = existing.CreatedAt
|
||||||
|
} else {
|
||||||
|
prefs.CreatedAt = now
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.repo.Upsert(ctx, prefs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.logger.Info("preferences upserted", "user_id", input.UserID)
|
||||||
|
return prefs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validatePreferences checks known preference keys against their allowed values.
|
||||||
|
func validatePreferences(prefs map[string]any) error {
|
||||||
|
details := make(map[string]string)
|
||||||
|
|
||||||
|
for key, value := range prefs {
|
||||||
|
switch key {
|
||||||
|
case "theme":
|
||||||
|
s, ok := value.(string)
|
||||||
|
if !ok || !validThemes[s] {
|
||||||
|
details[key] = "must be one of: light, dark, system"
|
||||||
|
}
|
||||||
|
case "language":
|
||||||
|
s, ok := value.(string)
|
||||||
|
if !ok {
|
||||||
|
details[key] = "must be a valid BCP-47 language tag"
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := language.Parse(s); err != nil {
|
||||||
|
details[key] = fmt.Sprintf("must be a valid BCP-47 language tag")
|
||||||
|
}
|
||||||
|
case "notifications_enabled":
|
||||||
|
if _, ok := value.(bool); !ok {
|
||||||
|
details[key] = "must be a boolean"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(details) > 0 {
|
||||||
|
return &ValidationError{Details: details}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
268
services/preferences-api/internal/service/preference_test.go
Normal file
268
services/preferences-api/internal/service/preference_test.go
Normal file
@ -0,0 +1,268 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/pkg/logging"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/domain"
|
||||||
|
"git.threesix.ai/jordan/slack5-1770606136/services/preferences-api/internal/port"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mockPreferenceRepository implements port.PreferenceRepository for testing.
|
||||||
|
type mockPreferenceRepository struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
prefs map[string]*domain.UserPreferences
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ port.PreferenceRepository = (*mockPreferenceRepository)(nil)
|
||||||
|
|
||||||
|
func newMockPreferenceRepository() *mockPreferenceRepository {
|
||||||
|
return &mockPreferenceRepository{
|
||||||
|
prefs: make(map[string]*domain.UserPreferences),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockPreferenceRepository) Get(ctx context.Context, userID string) (*domain.UserPreferences, error) {
|
||||||
|
m.mu.RLock()
|
||||||
|
defer m.mu.RUnlock()
|
||||||
|
|
||||||
|
p, ok := m.prefs[userID]
|
||||||
|
if !ok {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
// Return a copy
|
||||||
|
cp := *p
|
||||||
|
cpPrefs := make(map[string]any)
|
||||||
|
for k, v := range p.Preferences {
|
||||||
|
cpPrefs[k] = v
|
||||||
|
}
|
||||||
|
cp.Preferences = cpPrefs
|
||||||
|
return &cp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockPreferenceRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
cp := *prefs
|
||||||
|
cpPrefs := make(map[string]any)
|
||||||
|
for k, v := range prefs.Preferences {
|
||||||
|
cpPrefs[k] = v
|
||||||
|
}
|
||||||
|
cp.Preferences = cpPrefs
|
||||||
|
m.prefs[prefs.UserID] = &cp
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreferenceService_Get(t *testing.T) {
|
||||||
|
repo := newMockPreferenceRepository()
|
||||||
|
svc := NewPreferenceService(repo, logging.Nop())
|
||||||
|
|
||||||
|
t.Run("returns nil for non-existent user", func(t *testing.T) {
|
||||||
|
result, err := svc.Get(context.Background(), "user-1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if result != nil {
|
||||||
|
t.Error("expected nil result for non-existent user")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("returns existing preferences", func(t *testing.T) {
|
||||||
|
_, _ = svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-2",
|
||||||
|
Preferences: map[string]any{"theme": "dark"},
|
||||||
|
})
|
||||||
|
|
||||||
|
result, err := svc.Get(context.Background(), "user-2")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if result == nil {
|
||||||
|
t.Fatal("expected non-nil result")
|
||||||
|
}
|
||||||
|
if result.Preferences["theme"] != "dark" {
|
||||||
|
t.Errorf("expected theme 'dark', got '%v'", result.Preferences["theme"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreferenceService_Upsert(t *testing.T) {
|
||||||
|
repo := newMockPreferenceRepository()
|
||||||
|
svc := NewPreferenceService(repo, logging.Nop())
|
||||||
|
|
||||||
|
t.Run("creates preferences for new user", func(t *testing.T) {
|
||||||
|
result, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-1",
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"theme": "dark",
|
||||||
|
"language": "en",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if result.Preferences["theme"] != "dark" {
|
||||||
|
t.Errorf("expected theme 'dark', got '%v'", result.Preferences["theme"])
|
||||||
|
}
|
||||||
|
if result.Preferences["language"] != "en" {
|
||||||
|
t.Errorf("expected language 'en', got '%v'", result.Preferences["language"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("merges preferences with existing", func(t *testing.T) {
|
||||||
|
result, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-1",
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"notifications_enabled": true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
// Existing keys should be preserved
|
||||||
|
if result.Preferences["theme"] != "dark" {
|
||||||
|
t.Errorf("expected theme 'dark' preserved, got '%v'", result.Preferences["theme"])
|
||||||
|
}
|
||||||
|
if result.Preferences["language"] != "en" {
|
||||||
|
t.Errorf("expected language 'en' preserved, got '%v'", result.Preferences["language"])
|
||||||
|
}
|
||||||
|
// New key should be added
|
||||||
|
if result.Preferences["notifications_enabled"] != true {
|
||||||
|
t.Errorf("expected notifications_enabled true, got '%v'", result.Preferences["notifications_enabled"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("overwrites existing key", func(t *testing.T) {
|
||||||
|
result, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-1",
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"theme": "light",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if result.Preferences["theme"] != "light" {
|
||||||
|
t.Errorf("expected theme 'light', got '%v'", result.Preferences["theme"])
|
||||||
|
}
|
||||||
|
// Other keys preserved
|
||||||
|
if result.Preferences["language"] != "en" {
|
||||||
|
t.Errorf("expected language 'en' preserved, got '%v'", result.Preferences["language"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("accepts unknown keys without validation", func(t *testing.T) {
|
||||||
|
result, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-2",
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"custom_setting": "anything",
|
||||||
|
"sidebar_width": 42.0,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if result.Preferences["custom_setting"] != "anything" {
|
||||||
|
t.Errorf("expected custom_setting 'anything', got '%v'", result.Preferences["custom_setting"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("rejects invalid theme", func(t *testing.T) {
|
||||||
|
_, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-3",
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"theme": "neon",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for invalid theme")
|
||||||
|
}
|
||||||
|
if !errors.Is(err, domain.ErrInvalidPreferenceValue) {
|
||||||
|
t.Errorf("expected ErrInvalidPreferenceValue, got %v", err)
|
||||||
|
}
|
||||||
|
var valErr *ValidationError
|
||||||
|
if !errors.As(err, &valErr) {
|
||||||
|
t.Fatal("expected ValidationError type")
|
||||||
|
}
|
||||||
|
if valErr.Details["theme"] == "" {
|
||||||
|
t.Error("expected details for theme key")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("rejects invalid language", func(t *testing.T) {
|
||||||
|
_, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-3",
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"language": "not-a-language-!!!",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for invalid language")
|
||||||
|
}
|
||||||
|
var valErr *ValidationError
|
||||||
|
if !errors.As(err, &valErr) {
|
||||||
|
t.Fatal("expected ValidationError type")
|
||||||
|
}
|
||||||
|
if valErr.Details["language"] == "" {
|
||||||
|
t.Error("expected details for language key")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("rejects non-boolean notifications_enabled", func(t *testing.T) {
|
||||||
|
_, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-3",
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"notifications_enabled": "yes",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for non-boolean notifications_enabled")
|
||||||
|
}
|
||||||
|
var valErr *ValidationError
|
||||||
|
if !errors.As(err, &valErr) {
|
||||||
|
t.Fatal("expected ValidationError type")
|
||||||
|
}
|
||||||
|
if valErr.Details["notifications_enabled"] == "" {
|
||||||
|
t.Error("expected details for notifications_enabled key")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("collects multiple validation errors", func(t *testing.T) {
|
||||||
|
_, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-3",
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"theme": "invalid",
|
||||||
|
"notifications_enabled": "not-bool",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for multiple invalid values")
|
||||||
|
}
|
||||||
|
var valErr *ValidationError
|
||||||
|
if !errors.As(err, &valErr) {
|
||||||
|
t.Fatal("expected ValidationError type")
|
||||||
|
}
|
||||||
|
if len(valErr.Details) != 2 {
|
||||||
|
t.Errorf("expected 2 validation errors, got %d", len(valErr.Details))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("accepts valid BCP-47 tags", func(t *testing.T) {
|
||||||
|
validTags := []string{"en", "fr", "es", "de", "ja", "zh-Hans", "pt-BR"}
|
||||||
|
for _, tag := range validTags {
|
||||||
|
_, err := svc.Upsert(context.Background(), UpsertInput{
|
||||||
|
UserID: "user-lang-" + tag,
|
||||||
|
Preferences: map[string]any{
|
||||||
|
"language": tag,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("expected no error for valid BCP-47 tag '%s', got %v", tag, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
BIN
services/preferences-api/server
Executable file
BIN
services/preferences-api/server
Executable file
Binary file not shown.
Loading…
Reference in New Issue
Block a user