build: /implement-feature user-preferences
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
This commit is contained in:
parent
2ad9dcabd0
commit
e5fc44d10e
@ -1,7 +1,7 @@
|
||||
slug: user-preferences
|
||||
title: User Preferences API
|
||||
created: 2026-02-09T02:15:19.934404761Z
|
||||
phase: ready
|
||||
phase: implementation
|
||||
phase_history:
|
||||
- phase: draft
|
||||
entered: 2026-02-09T02:15:19.934404761Z
|
||||
@ -14,6 +14,9 @@ phase_history:
|
||||
exited: 2026-02-09T02:29:30.58699614Z
|
||||
- phase: ready
|
||||
entered: 2026-02-09T02:29:30.58699614Z
|
||||
exited: 2026-02-09T02:32:28.709423195Z
|
||||
- phase: implementation
|
||||
entered: 2026-02-09T02:32:28.709423195Z
|
||||
artifacts:
|
||||
audit:
|
||||
status: pending
|
||||
@ -45,22 +48,35 @@ artifacts:
|
||||
approved_by: user
|
||||
approved_at: 2026-02-09T02:26:14.114770656Z
|
||||
total: 6
|
||||
completed: 6
|
||||
tasks:
|
||||
- id: task-001
|
||||
title: Domain layer - preferences entity, validation, defaults, and errors
|
||||
status: pending
|
||||
status: complete
|
||||
started_at: 2026-02-09T02:32:33.046963423Z
|
||||
done_at: 2026-02-09T02:33:13.805844526Z
|
||||
- id: task-002
|
||||
title: Port layer - PreferencesRepository interface
|
||||
status: pending
|
||||
status: complete
|
||||
started_at: 2026-02-09T02:33:13.812394852Z
|
||||
done_at: 2026-02-09T02:33:27.291639357Z
|
||||
- id: task-003
|
||||
title: Service layer - PreferencesService with deep merge, get/update logic, and unit tests
|
||||
status: pending
|
||||
status: complete
|
||||
started_at: 2026-02-09T02:33:27.300268305Z
|
||||
done_at: 2026-02-09T02:34:22.01529497Z
|
||||
- id: task-004
|
||||
title: Database migration and PostgreSQL adapter
|
||||
status: pending
|
||||
status: complete
|
||||
started_at: 2026-02-09T02:34:22.023308991Z
|
||||
done_at: 2026-02-09T02:34:49.980516171Z
|
||||
- id: task-005
|
||||
title: HTTP handlers - GET and PUT preferences with request/response types and unit tests
|
||||
status: pending
|
||||
status: complete
|
||||
started_at: 2026-02-09T02:34:49.9863189Z
|
||||
done_at: 2026-02-09T02:35:44.499210123Z
|
||||
- id: task-006
|
||||
title: Wiring, routes, OpenAPI spec, and example scaffolding removal
|
||||
status: pending
|
||||
status: complete
|
||||
started_at: 2026-02-09T02:35:44.505187642Z
|
||||
done_at: 2026-02-09T02:37:21.440542135Z
|
||||
|
||||
@ -4,10 +4,10 @@ project:
|
||||
active_work:
|
||||
features:
|
||||
- slug: user-preferences
|
||||
phase: ready
|
||||
phase: implementation
|
||||
blocked: []
|
||||
last_updated: 2026-02-09T02:29:30.591850335Z
|
||||
last_action: TRANSITION
|
||||
last_updated: 2026-02-09T02:37:21.441656241Z
|
||||
last_action: COMPLETE_TASK
|
||||
last_actor: cli
|
||||
history:
|
||||
- timestamp: 2026-02-09T02:15:19.934883983Z
|
||||
@ -50,3 +50,38 @@ history:
|
||||
feature: user-preferences
|
||||
actor: cli
|
||||
result: success
|
||||
- timestamp: 2026-02-09T02:32:28.710231445Z
|
||||
action: TRANSITION
|
||||
feature: user-preferences
|
||||
actor: cli
|
||||
result: success
|
||||
- timestamp: 2026-02-09T02:33:13.806490391Z
|
||||
action: COMPLETE_TASK
|
||||
feature: user-preferences
|
||||
actor: cli
|
||||
result: success
|
||||
- timestamp: 2026-02-09T02:33:27.29240598Z
|
||||
action: COMPLETE_TASK
|
||||
feature: user-preferences
|
||||
actor: cli
|
||||
result: success
|
||||
- timestamp: 2026-02-09T02:34:22.017513745Z
|
||||
action: COMPLETE_TASK
|
||||
feature: user-preferences
|
||||
actor: cli
|
||||
result: success
|
||||
- timestamp: 2026-02-09T02:34:49.982589282Z
|
||||
action: COMPLETE_TASK
|
||||
feature: user-preferences
|
||||
actor: cli
|
||||
result: success
|
||||
- timestamp: 2026-02-09T02:35:44.499898649Z
|
||||
action: COMPLETE_TASK
|
||||
feature: user-preferences
|
||||
actor: cli
|
||||
result: success
|
||||
- timestamp: 2026-02-09T02:37:21.441655029Z
|
||||
action: COMPLETE_TASK
|
||||
feature: user-preferences
|
||||
actor: cli
|
||||
result: success
|
||||
|
||||
@ -2,17 +2,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/app"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/config"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/database"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/adapter/memory"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/adapter/postgres"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/api"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/service"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
func main() {
|
||||
// Parse flags
|
||||
exportOpenAPI := flag.Bool("export-openapi", false, "Export OpenAPI spec to stdout and exit")
|
||||
@ -33,17 +40,30 @@ func main() {
|
||||
// Create logger
|
||||
logger := logging.Default()
|
||||
|
||||
// Connect to PostgreSQL
|
||||
dbCfg := config.ReadDatabaseConfig()
|
||||
ctx := context.Background()
|
||||
pool := database.MustConnect(ctx, dbCfg.URL, database.Options{
|
||||
MaxOpenConns: dbCfg.MaxOpenConns,
|
||||
MaxIdleConns: dbCfg.MaxIdleConns,
|
||||
ConnMaxLifetime: dbCfg.ConnMaxLifetime,
|
||||
})
|
||||
defer pool.Close()
|
||||
|
||||
// Run migrations
|
||||
database.MustRunMigrations(ctx, pool, migrationsFS, "migrations")
|
||||
|
||||
// Create adapters (repositories)
|
||||
exampleRepo := memory.NewExampleRepository()
|
||||
preferencesRepo := postgres.NewPreferencesRepository(pool)
|
||||
|
||||
// Create services (business logic)
|
||||
exampleService := service.NewExampleService(exampleRepo, logger)
|
||||
preferencesService := service.NewPreferencesService(preferencesRepo, logger)
|
||||
|
||||
// Create application
|
||||
application := app.New("preferences-api", app.WithDefaultPort(8001))
|
||||
|
||||
// Register routes with dependency injection
|
||||
api.RegisterRoutes(application, exampleService)
|
||||
api.RegisterRoutes(application, preferencesService)
|
||||
|
||||
// Start server
|
||||
application.Run()
|
||||
|
||||
@ -0,0 +1,6 @@
|
||||
CREATE TABLE IF NOT EXISTS user_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()
|
||||
);
|
||||
@ -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-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/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,74 @@
|
||||
// Package postgres provides PostgreSQL implementations of repository interfaces.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/database"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/port"
|
||||
)
|
||||
|
||||
// Compile-time verification that PreferencesRepository implements port.PreferencesRepository.
|
||||
var _ port.PreferencesRepository = (*PreferencesRepository)(nil)
|
||||
|
||||
// PreferencesRepository is a PostgreSQL implementation of port.PreferencesRepository.
|
||||
type PreferencesRepository struct {
|
||||
pool *database.Pool
|
||||
}
|
||||
|
||||
// NewPreferencesRepository creates a new PostgreSQL preferences repository.
|
||||
func NewPreferencesRepository(pool *database.Pool) *PreferencesRepository {
|
||||
return &PreferencesRepository{pool: pool}
|
||||
}
|
||||
|
||||
// Get returns preferences for a user by ID.
|
||||
// Returns nil, nil if no preferences exist for the user.
|
||||
func (r *PreferencesRepository) Get(ctx context.Context, userID domain.UserID) (*domain.UserPreferences, error) {
|
||||
var prefsJSON []byte
|
||||
var updatedAt time.Time
|
||||
|
||||
err := r.pool.DB.QueryRowContext(ctx,
|
||||
`SELECT preferences, updated_at FROM user_preferences WHERE user_id = $1`,
|
||||
string(userID),
|
||||
).Scan(&prefsJSON, &updatedAt)
|
||||
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var prefs domain.Preferences
|
||||
if err := json.Unmarshal(prefsJSON, &prefs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &domain.UserPreferences{
|
||||
UserID: userID,
|
||||
Preferences: prefs,
|
||||
UpdatedAt: updatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Upsert creates or updates preferences for a user.
|
||||
func (r *PreferencesRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error {
|
||||
prefsJSON, err := json.Marshal(prefs.Preferences)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = r.pool.DB.ExecContext(ctx,
|
||||
`INSERT INTO user_preferences (user_id, preferences, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $3)
|
||||
ON CONFLICT (user_id)
|
||||
DO UPDATE SET preferences = $2, updated_at = $3`,
|
||||
string(prefs.UserID), prefsJSON, prefs.UpdatedAt,
|
||||
)
|
||||
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-1770603014/pkg/app"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/httperror"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/httpresponse"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/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-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/port"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
130
services/preferences-api/internal/api/handlers/preferences.go
Normal file
130
services/preferences-api/internal/api/handlers/preferences.go
Normal file
@ -0,0 +1,130 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/app"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/httperror"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/httpresponse"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/service"
|
||||
)
|
||||
|
||||
// Preferences handles HTTP requests for user preferences.
|
||||
type Preferences struct {
|
||||
svc *service.PreferencesService
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
// NewPreferences creates a new Preferences handler with injected dependencies.
|
||||
func NewPreferences(svc *service.PreferencesService, logger *logging.Logger) *Preferences {
|
||||
return &Preferences{
|
||||
svc: svc,
|
||||
logger: logger.WithComponent("PreferencesHandler"),
|
||||
}
|
||||
}
|
||||
|
||||
// UpdatePreferencesRequest is the request body for updating preferences.
|
||||
type UpdatePreferencesRequest struct {
|
||||
Preferences PreferencesInput `json:"preferences" validate:"required"`
|
||||
}
|
||||
|
||||
// PreferencesInput uses pointers to distinguish "not provided" from zero values.
|
||||
type PreferencesInput struct {
|
||||
Theme *string `json:"theme,omitempty"`
|
||||
Language *string `json:"language,omitempty"`
|
||||
Notifications *NotificationsInput `json:"notifications,omitempty"`
|
||||
}
|
||||
|
||||
// NotificationsInput uses pointers for partial update semantics.
|
||||
type NotificationsInput struct {
|
||||
Email *bool `json:"email,omitempty"`
|
||||
Push *bool `json:"push,omitempty"`
|
||||
Digest *string `json:"digest,omitempty"`
|
||||
}
|
||||
|
||||
// PreferencesResponse is the response for preferences endpoints.
|
||||
type PreferencesResponse struct {
|
||||
UserID string `json:"user_id"`
|
||||
Preferences domain.Preferences `json:"preferences"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// toPreferencesResponse converts a domain UserPreferences to an API response.
|
||||
func toPreferencesResponse(p *domain.UserPreferences) PreferencesResponse {
|
||||
return PreferencesResponse{
|
||||
UserID: p.UserID.String(),
|
||||
Preferences: p.Preferences,
|
||||
UpdatedAt: p.UpdatedAt.Format("2006-01-02T15:04:05Z"),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns preferences for a user.
|
||||
func (h *Preferences) 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.GetPreferences(r.Context(), domain.UserID(userID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
httpresponse.OK(w, r, toPreferencesResponse(prefs))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Upsert creates or updates preferences for a user.
|
||||
func (h *Preferences) 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.BindAndValidate(r, &req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
input := service.UpdateInput{
|
||||
Theme: req.Preferences.Theme,
|
||||
Language: req.Preferences.Language,
|
||||
}
|
||||
if req.Preferences.Notifications != nil {
|
||||
input.Notifications = &service.NotificationsInput{
|
||||
Email: req.Preferences.Notifications.Email,
|
||||
Push: req.Preferences.Notifications.Push,
|
||||
Digest: req.Preferences.Notifications.Digest,
|
||||
}
|
||||
}
|
||||
|
||||
prefs, err := h.svc.UpdatePreferences(r.Context(), domain.UserID(userID), input)
|
||||
if err != nil {
|
||||
return mapPreferencesDomainError(err)
|
||||
}
|
||||
|
||||
httpresponse.OK(w, r, toPreferencesResponse(prefs))
|
||||
return nil
|
||||
}
|
||||
|
||||
// mapPreferencesDomainError converts domain errors to HTTP errors.
|
||||
func mapPreferencesDomainError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrInvalidTheme):
|
||||
return httperror.BadRequest(err.Error())
|
||||
case errors.Is(err, domain.ErrInvalidLanguage):
|
||||
return httperror.BadRequest(err.Error())
|
||||
case errors.Is(err, domain.ErrInvalidDigest):
|
||||
return httperror.BadRequest(err.Error())
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,274 @@
|
||||
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-1770603014/pkg/app"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/port"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/service"
|
||||
)
|
||||
|
||||
// mockPreferencesRepository implements port.PreferencesRepository for testing.
|
||||
type mockPreferencesRepository struct {
|
||||
mu sync.RWMutex
|
||||
store map[domain.UserID]*domain.UserPreferences
|
||||
}
|
||||
|
||||
var _ port.PreferencesRepository = (*mockPreferencesRepository)(nil)
|
||||
|
||||
func newMockPreferencesRepository() *mockPreferencesRepository {
|
||||
return &mockPreferencesRepository{
|
||||
store: make(map[domain.UserID]*domain.UserPreferences),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mockPreferencesRepository) Get(ctx context.Context, userID domain.UserID) (*domain.UserPreferences, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
p, ok := m.store[userID]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
cp := *p
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (m *mockPreferencesRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
cp := *prefs
|
||||
m.store[prefs.UserID] = &cp
|
||||
return nil
|
||||
}
|
||||
|
||||
func newTestPreferencesHandler() (*Preferences, *mockPreferencesRepository) {
|
||||
repo := newMockPreferencesRepository()
|
||||
svc := service.NewPreferencesService(repo, logging.Nop())
|
||||
handler := NewPreferences(svc, logging.Nop())
|
||||
return handler, repo
|
||||
}
|
||||
|
||||
func TestPreferences_Get(t *testing.T) {
|
||||
handler, repo := newTestPreferencesHandler()
|
||||
|
||||
// Seed data for existing user
|
||||
repo.mu.Lock()
|
||||
repo.store["550e8400-e29b-41d4-a716-446655440000"] = &domain.UserPreferences{
|
||||
UserID: "550e8400-e29b-41d4-a716-446655440000",
|
||||
Preferences: domain.Preferences{
|
||||
Theme: "dark",
|
||||
Language: "fr",
|
||||
Notifications: domain.NotificationSettings{
|
||||
Email: false,
|
||||
Push: true,
|
||||
Digest: "daily",
|
||||
},
|
||||
},
|
||||
}
|
||||
repo.mu.Unlock()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
userID string
|
||||
wantStatus int
|
||||
checkBody func(t *testing.T, body map[string]any)
|
||||
}{
|
||||
{
|
||||
name: "returns stored 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' object in response")
|
||||
}
|
||||
prefs, ok := data["preferences"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatal("expected 'preferences' object in data")
|
||||
}
|
||||
if prefs["theme"] != "dark" {
|
||||
t.Errorf("expected theme 'dark', got '%v'", prefs["theme"])
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "returns defaults 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' object in response")
|
||||
}
|
||||
prefs, ok := data["preferences"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatal("expected 'preferences' object in data")
|
||||
}
|
||||
if prefs["theme"] != "system" {
|
||||
t.Errorf("expected theme 'system', got '%v'", prefs["theme"])
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
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("/api/preferences-api/preferences/{user_id}", app.Wrap(handler.Get))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/preferences-api/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 {
|
||||
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 TestPreferences_Upsert(t *testing.T) {
|
||||
handler, _ := newTestPreferencesHandler()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
userID string
|
||||
body any
|
||||
wantStatus int
|
||||
checkBody func(t *testing.T, body map[string]any)
|
||||
}{
|
||||
{
|
||||
name: "creates preferences with full update",
|
||||
userID: "550e8400-e29b-41d4-a716-446655440000",
|
||||
body: map[string]any{
|
||||
"preferences": map[string]any{
|
||||
"theme": "dark",
|
||||
"language": "fr",
|
||||
"notifications": map[string]any{
|
||||
"email": false,
|
||||
"push": true,
|
||||
"digest": "daily",
|
||||
},
|
||||
},
|
||||
},
|
||||
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' object in response")
|
||||
}
|
||||
prefs, ok := data["preferences"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatal("expected 'preferences' object in data")
|
||||
}
|
||||
if prefs["theme"] != "dark" {
|
||||
t.Errorf("expected theme 'dark', got '%v'", prefs["theme"])
|
||||
}
|
||||
if prefs["language"] != "fr" {
|
||||
t.Errorf("expected language 'fr', got '%v'", prefs["language"])
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "creates preferences with partial update",
|
||||
userID: "550e8400-e29b-41d4-a716-446655440002",
|
||||
body: map[string]any{
|
||||
"preferences": map[string]any{
|
||||
"theme": "light",
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusOK,
|
||||
checkBody: func(t *testing.T, body map[string]any) {
|
||||
data := body["data"].(map[string]any)
|
||||
prefs := data["preferences"].(map[string]any)
|
||||
if prefs["theme"] != "light" {
|
||||
t.Errorf("expected theme 'light', got '%v'", prefs["theme"])
|
||||
}
|
||||
// Language should be default
|
||||
if prefs["language"] != "en" {
|
||||
t.Errorf("expected default language 'en', got '%v'", prefs["language"])
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "returns 400 for invalid UUID",
|
||||
userID: "not-a-uuid",
|
||||
body: map[string]any{"preferences": map[string]any{"theme": "dark"}},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "returns 400 for invalid theme",
|
||||
userID: "550e8400-e29b-41d4-a716-446655440003",
|
||||
body: map[string]any{
|
||||
"preferences": map[string]any{
|
||||
"theme": "purple",
|
||||
},
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "returns 400 for empty body",
|
||||
userID: "550e8400-e29b-41d4-a716-446655440004",
|
||||
body: nil,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := chi.NewRouter()
|
||||
r.Put("/api/preferences-api/preferences/{user_id}", app.Wrap(handler.Upsert))
|
||||
|
||||
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, "/api/preferences-api/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 {
|
||||
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,24 +3,18 @@ package api
|
||||
|
||||
import (
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/app"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/auth"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/api/handlers"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/config"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/service"
|
||||
)
|
||||
|
||||
// RegisterRoutes registers all HTTP routes for the service.
|
||||
// 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:
|
||||
// - https://domain/api/preferences-api/health
|
||||
// - https://domain/api/preferences-api/examples
|
||||
func RegisterRoutes(application *app.App, exampleService *service.ExampleService) {
|
||||
func RegisterRoutes(application *app.App, preferencesService *service.PreferencesService) {
|
||||
logger := application.Logger()
|
||||
cfg := config.Load()
|
||||
|
||||
// Initialize handlers with injected services
|
||||
healthHandler := handlers.NewHealth(logger)
|
||||
exampleHandler := handlers.NewExample(exampleService, logger)
|
||||
preferencesHandler := handlers.NewPreferences(preferencesService, logger)
|
||||
|
||||
// Build and mount OpenAPI spec
|
||||
spec := NewServiceSpec()
|
||||
@ -31,24 +25,8 @@ func RegisterRoutes(application *app.App, exampleService *service.ExampleService
|
||||
application.Route("/api/preferences-api", func(r app.Router) {
|
||||
r.Get("/health", healthHandler.Check)
|
||||
|
||||
// Public routes (no auth required)
|
||||
r.Get("/examples", app.Wrap(exampleHandler.List))
|
||||
r.Get("/examples/{id}", app.Wrap(exampleHandler.Get))
|
||||
|
||||
// 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-1770603014",
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
r.Post("/examples", app.Wrap(exampleHandler.Create))
|
||||
r.Put("/examples/{id}", app.Wrap(exampleHandler.Update))
|
||||
r.Delete("/examples/{id}", app.Wrap(exampleHandler.Delete))
|
||||
})
|
||||
// Public routes (no auth required per spec)
|
||||
r.Get("/preferences/{user_id}", app.Wrap(preferencesHandler.Get))
|
||||
r.Put("/preferences/{user_id}", app.Wrap(preferencesHandler.Upsert))
|
||||
})
|
||||
}
|
||||
|
||||
@ -5,29 +5,42 @@ import "git.threesix.ai/jordan/slack5-1770603014/pkg/openapi"
|
||||
// NewServiceSpec builds the OpenAPI specification for the preferences-api service.
|
||||
func NewServiceSpec() *openapi.OpenAPISpec {
|
||||
spec := openapi.NewOpenAPISpec("preferences-api API", "1.0.0").
|
||||
WithDescription("REST API for the preferences-api service").
|
||||
WithBearerSecurity("bearer", "JWT authentication token").
|
||||
WithDescription("REST API for the preferences-api service - user preferences management").
|
||||
WithTag("Health", "Service health endpoints").
|
||||
WithTag("Examples", "Example CRUD endpoints")
|
||||
WithTag("Preferences", "User preferences endpoints")
|
||||
|
||||
// Define reusable schemas
|
||||
spec.WithSchema("Example", openapi.Object(map[string]openapi.Schema{
|
||||
"id": openapi.UUID().WithDescription("Unique identifier"),
|
||||
"name": openapi.String().WithDescription("Name of the example").WithExample("My Example"),
|
||||
"description": openapi.String().WithDescription("Optional description").WithExample("A description"),
|
||||
"created_at": openapi.DateTime().WithDescription("Creation timestamp"),
|
||||
notificationSettings := openapi.Object(map[string]openapi.Schema{
|
||||
"email": openapi.Bool().WithDescription("Email notifications enabled"),
|
||||
"push": openapi.Bool().WithDescription("Push notifications enabled"),
|
||||
"digest": openapi.StringEnum("daily", "weekly", "never").WithDescription("Digest frequency"),
|
||||
})
|
||||
|
||||
preferencesSchema := openapi.Object(map[string]openapi.Schema{
|
||||
"theme": openapi.StringEnum("light", "dark", "system").WithDescription("UI theme"),
|
||||
"language": openapi.String().WithDescription("BCP 47 language tag"),
|
||||
"notifications": notificationSettings,
|
||||
})
|
||||
|
||||
spec.WithSchema("PreferencesResponse", openapi.Object(map[string]openapi.Schema{
|
||||
"user_id": openapi.UUID().WithDescription("User identifier"),
|
||||
"preferences": preferencesSchema,
|
||||
"updated_at": openapi.DateTime().WithDescription("Last update timestamp"),
|
||||
}, "id", "name"))
|
||||
}, "user_id", "preferences", "updated_at"))
|
||||
|
||||
spec.WithSchema("CreateExampleRequest", openapi.Object(map[string]openapi.Schema{
|
||||
"name": openapi.StringWithMinMax(1, 100).WithDescription("Name of the example"),
|
||||
"description": openapi.StringWithMinMax(0, 500).WithDescription("Optional description"),
|
||||
}, "name"))
|
||||
spec.WithSchema("UpdatePreferencesRequest", openapi.Object(map[string]openapi.Schema{
|
||||
"preferences": openapi.Object(map[string]openapi.Schema{
|
||||
"theme": openapi.StringEnum("light", "dark", "system").WithDescription("UI theme"),
|
||||
"language": openapi.String().WithDescription("BCP 47 language tag"),
|
||||
"notifications": openapi.Object(map[string]openapi.Schema{
|
||||
"email": openapi.Bool().WithDescription("Email notifications enabled"),
|
||||
"push": openapi.Bool().WithDescription("Push notifications enabled"),
|
||||
"digest": openapi.StringEnum("daily", "weekly", "never").WithDescription("Digest frequency"),
|
||||
}),
|
||||
}),
|
||||
}, "preferences"))
|
||||
|
||||
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"),
|
||||
}))
|
||||
userIDParam := openapi.PathParam("user_id", "User UUID identifier")
|
||||
|
||||
// Health
|
||||
spec.AddPath("/api/preferences-api/health", "get", map[string]any{
|
||||
@ -41,70 +54,28 @@ func NewServiceSpec() *openapi.OpenAPISpec {
|
||||
},
|
||||
})
|
||||
|
||||
// List examples
|
||||
spec.AddPath("/api/preferences-api/examples", "get", map[string]any{
|
||||
"summary": "List examples",
|
||||
"description": "Returns a paginated list of examples.",
|
||||
"tags": []string{"Examples"},
|
||||
"parameters": []any{openapi.PageParam(), openapi.PerPageParam()},
|
||||
// Get preferences
|
||||
spec.AddPath("/api/preferences-api/preferences/{user_id}", "get", map[string]any{
|
||||
"summary": "Get user preferences",
|
||||
"description": "Returns preferences for a user. Returns defaults if no preferences are stored.",
|
||||
"tags": []string{"Preferences"},
|
||||
"parameters": []any{userIDParam},
|
||||
"responses": map[string]any{
|
||||
"200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.RefArray("Example"))),
|
||||
"200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.Ref("PreferencesResponse"))),
|
||||
"400": openapi.OpResponse("Invalid user_id format", openapi.ErrorResponseSchema()),
|
||||
},
|
||||
})
|
||||
|
||||
// Get example
|
||||
spec.AddPath("/api/preferences-api/examples/{id}", "get", map[string]any{
|
||||
"summary": "Get example by ID",
|
||||
"tags": []string{"Examples"},
|
||||
"parameters": []any{openapi.IDParam()},
|
||||
// Update preferences
|
||||
spec.AddPath("/api/preferences-api/preferences/{user_id}", "put", map[string]any{
|
||||
"summary": "Update user preferences",
|
||||
"description": "Creates or updates preferences for a user. Performs a deep merge with existing preferences - only provided keys are changed.",
|
||||
"tags": []string{"Preferences"},
|
||||
"parameters": []any{userIDParam},
|
||||
"requestBody": openapi.RequestBody(openapi.Ref("UpdatePreferencesRequest"), true),
|
||||
"responses": map[string]any{
|
||||
"200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.Ref("Example"))),
|
||||
"404": openapi.OpResponse("Not found", 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()),
|
||||
"200": openapi.OpResponse("Success", openapi.ResponseSchema(openapi.Ref("PreferencesResponse"))),
|
||||
"400": openapi.OpResponse("Invalid request", openapi.ErrorResponseSchema()),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@ -7,15 +7,12 @@ import "errors"
|
||||
// Domain errors - these are business-level errors that should be translated
|
||||
// to appropriate HTTP status codes by the handler layer.
|
||||
var (
|
||||
// ErrNotFound indicates a requested resource does not exist.
|
||||
ErrNotFound = errors.New("not found")
|
||||
// ErrInvalidTheme indicates the theme value is not one of: light, dark, system.
|
||||
ErrInvalidTheme = errors.New("invalid theme: must be light, dark, or system")
|
||||
|
||||
// ErrExampleNotFound indicates the requested example does not exist.
|
||||
ErrExampleNotFound = errors.New("example not found")
|
||||
// ErrInvalidLanguage indicates the language value is empty.
|
||||
ErrInvalidLanguage = errors.New("invalid language: must be non-empty")
|
||||
|
||||
// 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")
|
||||
// ErrInvalidDigest indicates the digest value is not one of: daily, weekly, never.
|
||||
ErrInvalidDigest = errors.New("invalid digest: must be daily, weekly, or never")
|
||||
)
|
||||
|
||||
@ -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
|
||||
}
|
||||
65
services/preferences-api/internal/domain/preferences.go
Normal file
65
services/preferences-api/internal/domain/preferences.go
Normal file
@ -0,0 +1,65 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
// UserID is a strongly-typed identifier for users.
|
||||
type UserID string
|
||||
|
||||
// String returns the string representation of the UserID.
|
||||
func (id UserID) String() string {
|
||||
return string(id)
|
||||
}
|
||||
|
||||
// Preferences holds the user's preference settings.
|
||||
type Preferences struct {
|
||||
Theme string `json:"theme"`
|
||||
Language string `json:"language"`
|
||||
Notifications NotificationSettings `json:"notifications"`
|
||||
}
|
||||
|
||||
// NotificationSettings holds notification-related preferences.
|
||||
type NotificationSettings struct {
|
||||
Email bool `json:"email"`
|
||||
Push bool `json:"push"`
|
||||
Digest string `json:"digest"`
|
||||
}
|
||||
|
||||
// UserPreferences is the domain entity representing a user's full preference record.
|
||||
type UserPreferences struct {
|
||||
UserID UserID
|
||||
Preferences Preferences
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// DefaultPreferences returns the default preference values.
|
||||
func DefaultPreferences() Preferences {
|
||||
return Preferences{
|
||||
Theme: "system",
|
||||
Language: "en",
|
||||
Notifications: NotificationSettings{
|
||||
Email: true,
|
||||
Push: true,
|
||||
Digest: "weekly",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Allowed values.
|
||||
var (
|
||||
allowedThemes = map[string]bool{"light": true, "dark": true, "system": true}
|
||||
allowedDigests = map[string]bool{"daily": true, "weekly": true, "never": true}
|
||||
)
|
||||
|
||||
// Validate checks that all preference values are valid.
|
||||
func (p *Preferences) Validate() error {
|
||||
if !allowedThemes[p.Theme] {
|
||||
return ErrInvalidTheme
|
||||
}
|
||||
if p.Language == "" {
|
||||
return ErrInvalidLanguage
|
||||
}
|
||||
if !allowedDigests[p.Notifications.Digest] {
|
||||
return ErrInvalidDigest
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -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-1770603014/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)
|
||||
}
|
||||
21
services/preferences-api/internal/port/preferences.go
Normal file
21
services/preferences-api/internal/port/preferences.go
Normal file
@ -0,0 +1,21 @@
|
||||
// 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-1770603014/services/preferences-api/internal/domain"
|
||||
)
|
||||
|
||||
// PreferencesRepository defines the interface for preferences persistence operations.
|
||||
// Implementations may use databases, in-memory storage, or external services.
|
||||
type PreferencesRepository interface {
|
||||
// Get returns preferences for a user by ID.
|
||||
// Returns nil, nil if no preferences exist for the user.
|
||||
Get(ctx context.Context, userID domain.UserID) (*domain.UserPreferences, error)
|
||||
|
||||
// Upsert creates or updates preferences for a user.
|
||||
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-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/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-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/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))
|
||||
}
|
||||
})
|
||||
}
|
||||
114
services/preferences-api/internal/service/preferences.go
Normal file
114
services/preferences-api/internal/service/preferences.go
Normal file
@ -0,0 +1,114 @@
|
||||
// Package service provides business logic / use cases for the application.
|
||||
// Services orchestrate domain operations using port interfaces.
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/port"
|
||||
)
|
||||
|
||||
// PreferencesService handles preferences-related business logic.
|
||||
type PreferencesService struct {
|
||||
repo port.PreferencesRepository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
// NewPreferencesService creates a new preferences service.
|
||||
func NewPreferencesService(repo port.PreferencesRepository, logger *logging.Logger) *PreferencesService {
|
||||
return &PreferencesService{
|
||||
repo: repo,
|
||||
logger: logger.WithService("PreferencesService"),
|
||||
}
|
||||
}
|
||||
|
||||
// GetPreferences returns preferences for a user. Returns defaults if none are stored.
|
||||
func (s *PreferencesService) GetPreferences(ctx context.Context, userID domain.UserID) (*domain.UserPreferences, error) {
|
||||
prefs, err := s.repo.Get(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if prefs != nil {
|
||||
return prefs, nil
|
||||
}
|
||||
|
||||
// Return defaults for unknown users
|
||||
return &domain.UserPreferences{
|
||||
UserID: userID,
|
||||
Preferences: domain.DefaultPreferences(),
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateInput contains the partial preference data for an update.
|
||||
// Pointer fields distinguish "not provided" from zero values.
|
||||
type UpdateInput struct {
|
||||
Theme *string
|
||||
Language *string
|
||||
Notifications *NotificationsInput
|
||||
}
|
||||
|
||||
// NotificationsInput contains partial notification settings.
|
||||
type NotificationsInput struct {
|
||||
Email *bool
|
||||
Push *bool
|
||||
Digest *string
|
||||
}
|
||||
|
||||
// UpdatePreferences merges partial input with existing preferences and persists.
|
||||
func (s *PreferencesService) UpdatePreferences(ctx context.Context, userID domain.UserID, input UpdateInput) (*domain.UserPreferences, error) {
|
||||
// Fetch existing or start from defaults
|
||||
existing, err := s.repo.Get(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var merged domain.Preferences
|
||||
if existing != nil {
|
||||
merged = existing.Preferences
|
||||
} else {
|
||||
merged = domain.DefaultPreferences()
|
||||
}
|
||||
|
||||
// Deep merge incoming fields
|
||||
if input.Theme != nil {
|
||||
merged.Theme = *input.Theme
|
||||
}
|
||||
if input.Language != nil {
|
||||
merged.Language = *input.Language
|
||||
}
|
||||
if input.Notifications != nil {
|
||||
if input.Notifications.Email != nil {
|
||||
merged.Notifications.Email = *input.Notifications.Email
|
||||
}
|
||||
if input.Notifications.Push != nil {
|
||||
merged.Notifications.Push = *input.Notifications.Push
|
||||
}
|
||||
if input.Notifications.Digest != nil {
|
||||
merged.Notifications.Digest = *input.Notifications.Digest
|
||||
}
|
||||
}
|
||||
|
||||
// Validate merged result
|
||||
if err := merged.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
prefs := &domain.UserPreferences{
|
||||
UserID: userID,
|
||||
Preferences: merged,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
if err := s.repo.Upsert(ctx, prefs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.logger.Info("preferences updated", "user_id", userID)
|
||||
return prefs, nil
|
||||
}
|
||||
253
services/preferences-api/internal/service/preferences_test.go
Normal file
253
services/preferences-api/internal/service/preferences_test.go
Normal file
@ -0,0 +1,253 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.threesix.ai/jordan/slack5-1770603014/pkg/logging"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/domain"
|
||||
"git.threesix.ai/jordan/slack5-1770603014/services/preferences-api/internal/port"
|
||||
)
|
||||
|
||||
// mockPreferencesRepository implements port.PreferencesRepository for testing.
|
||||
type mockPreferencesRepository struct {
|
||||
mu sync.RWMutex
|
||||
store map[domain.UserID]*domain.UserPreferences
|
||||
}
|
||||
|
||||
var _ port.PreferencesRepository = (*mockPreferencesRepository)(nil)
|
||||
|
||||
func newMockPreferencesRepository() *mockPreferencesRepository {
|
||||
return &mockPreferencesRepository{
|
||||
store: make(map[domain.UserID]*domain.UserPreferences),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mockPreferencesRepository) Get(ctx context.Context, userID domain.UserID) (*domain.UserPreferences, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
p, ok := m.store[userID]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
cp := *p
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (m *mockPreferencesRepository) Upsert(ctx context.Context, prefs *domain.UserPreferences) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
cp := *prefs
|
||||
m.store[prefs.UserID] = &cp
|
||||
return nil
|
||||
}
|
||||
|
||||
func strPtr(s string) *string { return &s }
|
||||
func boolPtr(b bool) *bool { return &b }
|
||||
|
||||
func TestPreferencesService_GetPreferences(t *testing.T) {
|
||||
repo := newMockPreferencesRepository()
|
||||
svc := NewPreferencesService(repo, logging.Nop())
|
||||
|
||||
t.Run("returns defaults for unknown user", func(t *testing.T) {
|
||||
prefs, err := svc.GetPreferences(context.Background(), "unknown-user")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if prefs.Preferences.Theme != "system" {
|
||||
t.Errorf("expected theme 'system', got '%s'", prefs.Preferences.Theme)
|
||||
}
|
||||
if prefs.Preferences.Language != "en" {
|
||||
t.Errorf("expected language 'en', got '%s'", prefs.Preferences.Language)
|
||||
}
|
||||
if prefs.Preferences.Notifications.Email != true {
|
||||
t.Error("expected notifications.email true")
|
||||
}
|
||||
if prefs.Preferences.Notifications.Push != true {
|
||||
t.Error("expected notifications.push true")
|
||||
}
|
||||
if prefs.Preferences.Notifications.Digest != "weekly" {
|
||||
t.Errorf("expected notifications.digest 'weekly', got '%s'", prefs.Preferences.Notifications.Digest)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returns stored preferences for existing user", func(t *testing.T) {
|
||||
// Seed data
|
||||
repo.mu.Lock()
|
||||
repo.store["user-1"] = &domain.UserPreferences{
|
||||
UserID: "user-1",
|
||||
Preferences: domain.Preferences{
|
||||
Theme: "dark",
|
||||
Language: "fr",
|
||||
Notifications: domain.NotificationSettings{
|
||||
Email: false,
|
||||
Push: true,
|
||||
Digest: "daily",
|
||||
},
|
||||
},
|
||||
}
|
||||
repo.mu.Unlock()
|
||||
|
||||
prefs, err := svc.GetPreferences(context.Background(), "user-1")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if prefs.Preferences.Theme != "dark" {
|
||||
t.Errorf("expected theme 'dark', got '%s'", prefs.Preferences.Theme)
|
||||
}
|
||||
if prefs.Preferences.Language != "fr" {
|
||||
t.Errorf("expected language 'fr', got '%s'", prefs.Preferences.Language)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPreferencesService_UpdatePreferences(t *testing.T) {
|
||||
repo := newMockPreferencesRepository()
|
||||
svc := NewPreferencesService(repo, logging.Nop())
|
||||
|
||||
t.Run("creates new preferences from defaults", func(t *testing.T) {
|
||||
prefs, err := svc.UpdatePreferences(context.Background(), "new-user", UpdateInput{
|
||||
Theme: strPtr("dark"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if prefs.Preferences.Theme != "dark" {
|
||||
t.Errorf("expected theme 'dark', got '%s'", prefs.Preferences.Theme)
|
||||
}
|
||||
// Other fields should be defaults
|
||||
if prefs.Preferences.Language != "en" {
|
||||
t.Errorf("expected language 'en', got '%s'", prefs.Preferences.Language)
|
||||
}
|
||||
if prefs.Preferences.Notifications.Digest != "weekly" {
|
||||
t.Errorf("expected digest 'weekly', got '%s'", prefs.Preferences.Notifications.Digest)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("merges partial data with existing preferences", func(t *testing.T) {
|
||||
// First set full preferences
|
||||
_, _ = svc.UpdatePreferences(context.Background(), "merge-user", UpdateInput{
|
||||
Theme: strPtr("light"),
|
||||
Language: strPtr("es"),
|
||||
Notifications: &NotificationsInput{
|
||||
Email: boolPtr(false),
|
||||
Push: boolPtr(false),
|
||||
Digest: strPtr("daily"),
|
||||
},
|
||||
})
|
||||
|
||||
// Now partial update - only change push notification
|
||||
prefs, err := svc.UpdatePreferences(context.Background(), "merge-user", UpdateInput{
|
||||
Notifications: &NotificationsInput{
|
||||
Push: boolPtr(true),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Push should be updated
|
||||
if prefs.Preferences.Notifications.Push != true {
|
||||
t.Error("expected notifications.push true")
|
||||
}
|
||||
// Other fields should be unchanged
|
||||
if prefs.Preferences.Theme != "light" {
|
||||
t.Errorf("expected theme 'light', got '%s'", prefs.Preferences.Theme)
|
||||
}
|
||||
if prefs.Preferences.Language != "es" {
|
||||
t.Errorf("expected language 'es', got '%s'", prefs.Preferences.Language)
|
||||
}
|
||||
if prefs.Preferences.Notifications.Email != false {
|
||||
t.Error("expected notifications.email false")
|
||||
}
|
||||
if prefs.Preferences.Notifications.Digest != "daily" {
|
||||
t.Errorf("expected digest 'daily', got '%s'", prefs.Preferences.Notifications.Digest)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("updates theme only", func(t *testing.T) {
|
||||
prefs, err := svc.UpdatePreferences(context.Background(), "theme-user", UpdateInput{
|
||||
Theme: strPtr("light"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if prefs.Preferences.Theme != "light" {
|
||||
t.Errorf("expected theme 'light', got '%s'", prefs.Preferences.Theme)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("updates language only", func(t *testing.T) {
|
||||
prefs, err := svc.UpdatePreferences(context.Background(), "lang-user", UpdateInput{
|
||||
Language: strPtr("fr"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if prefs.Preferences.Language != "fr" {
|
||||
t.Errorf("expected language 'fr', got '%s'", prefs.Preferences.Language)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("updates all fields together", func(t *testing.T) {
|
||||
prefs, err := svc.UpdatePreferences(context.Background(), "all-user", UpdateInput{
|
||||
Theme: strPtr("dark"),
|
||||
Language: strPtr("de"),
|
||||
Notifications: &NotificationsInput{
|
||||
Email: boolPtr(false),
|
||||
Push: boolPtr(true),
|
||||
Digest: strPtr("never"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if prefs.Preferences.Theme != "dark" {
|
||||
t.Errorf("expected theme 'dark', got '%s'", prefs.Preferences.Theme)
|
||||
}
|
||||
if prefs.Preferences.Language != "de" {
|
||||
t.Errorf("expected language 'de', got '%s'", prefs.Preferences.Language)
|
||||
}
|
||||
if prefs.Preferences.Notifications.Email != false {
|
||||
t.Error("expected notifications.email false")
|
||||
}
|
||||
if prefs.Preferences.Notifications.Push != true {
|
||||
t.Error("expected notifications.push true")
|
||||
}
|
||||
if prefs.Preferences.Notifications.Digest != "never" {
|
||||
t.Errorf("expected digest 'never', got '%s'", prefs.Preferences.Notifications.Digest)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rejects invalid theme", func(t *testing.T) {
|
||||
_, err := svc.UpdatePreferences(context.Background(), "invalid-theme-user", UpdateInput{
|
||||
Theme: strPtr("purple"),
|
||||
})
|
||||
if err != domain.ErrInvalidTheme {
|
||||
t.Errorf("expected ErrInvalidTheme, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rejects invalid digest", func(t *testing.T) {
|
||||
_, err := svc.UpdatePreferences(context.Background(), "invalid-digest-user", UpdateInput{
|
||||
Notifications: &NotificationsInput{
|
||||
Digest: strPtr("monthly"),
|
||||
},
|
||||
})
|
||||
if err != domain.ErrInvalidDigest {
|
||||
t.Errorf("expected ErrInvalidDigest, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rejects empty language", func(t *testing.T) {
|
||||
_, err := svc.UpdatePreferences(context.Background(), "empty-lang-user", UpdateInput{
|
||||
Language: strPtr(""),
|
||||
})
|
||||
if err != domain.ErrInvalidLanguage {
|
||||
t.Errorf("expected ErrInvalidLanguage, got %v", 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