Files
apocapoc-api/internal/infrastructure/http/router.go
T
david aa8f7af55d feat: implement offline sync endpoints with Last-Write-Wins strategy
Add comprehensive offline synchronization support for habits and entries:

## Infrastructure (Phase 1)
- Add UpdatedAt and DeletedAt timestamps to Habit and HabitEntry entities
- Implement soft delete with Delete(), Touch(), and IsDeleted() methods
- Create SQL migration with optimized composite indexes for sync queries
- Add GetChangesSince() and SoftDelete() to both repositories
- Update all Find* methods to exclude soft-deleted records
- 13 comprehensive TDD tests for sync repository methods

## HTTP Endpoints (Phase 2)
- GET /api/v1/sync/changes: retrieve all changes since timestamp
- POST /api/v1/sync/batch: apply client changes with conflict resolution
- Implement Last-Write-Wins strategy using UpdatedAt timestamps
- Add authentication and rate limiting (100 req/min)
- Validate user ownership for all sync operations
- 9 tests for sync handlers (3 queries + 6 commands)

## Technical Details
- Composite indexes: (user_id, updated_at) for optimal query performance
- No pagination: atomic sync operations for data consistency
- Upsert behavior: create resources if not found on server
- DTOs with full entity state including timestamps
- Swagger documentation updated for new endpoints

All 220+ tests passing ✓
2025-12-12 00:11:46 +01:00

98 lines
3.2 KiB
Go

package http
import (
"net/http"
"time"
"apocapoc-api/internal/i18n"
"apocapoc-api/internal/infrastructure/auth"
"apocapoc-api/internal/infrastructure/logger"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/httprate"
httpSwagger "github.com/swaggo/http-swagger"
_ "apocapoc-api/docs"
)
func NewRouter(appURL string, habitHandlers *HabitHandlers, authHandlers *AuthHandlers, statsHandlers *StatsHandlers, healthHandlers *HealthHandlers, userHandlers *UserHandlers, exportHandlers *ExportHandlers, syncHandlers *SyncHandlers, jwtService *auth.JWTService, translator *i18n.Translator) *chi.Mux {
r := chi.NewRouter()
r.Use(logger.Middleware)
r.Use(middleware.Recoverer)
r.Use(i18n.LanguageMiddleware(translator))
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{appURL},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "Accept-Language"},
AllowCredentials: true,
}))
r.Get("/api/v1/docs", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/api/v1/docs/index.html", http.StatusMovedPermanently)
})
r.Get("/api/v1/docs/*", httpSwagger.Handler(
httpSwagger.URL("/api/v1/docs/doc.json"),
))
r.Get("/api/v1/health", healthHandlers.Health)
r.Route("/api/v1/auth", func(r chi.Router) {
r.Use(httprate.LimitByIP(10, 1*time.Minute))
r.Post("/register", authHandlers.Register)
r.Post("/login", authHandlers.Login)
r.Post("/refresh", authHandlers.Refresh)
r.Post("/logout", authHandlers.Logout)
r.Post("/verify-email", authHandlers.VerifyEmail)
r.Post("/resend-verification", authHandlers.ResendVerification)
r.With(RateLimitByEmail(3, 1*time.Hour)).Post("/forgot-password", authHandlers.ForgotPassword)
r.Post("/reset-password", authHandlers.ResetPassword)
})
r.Route("/api/v1/habits", func(r chi.Router) {
r.Use(AuthMiddleware(jwtService))
r.Use(RateLimitByUser(jwtService, 100, 1*time.Minute))
r.Post("/", habitHandlers.CreateHabit)
r.Get("/", habitHandlers.GetUserHabits)
r.Get("/today", habitHandlers.GetTodaysHabits)
r.Get("/{id}", habitHandlers.GetHabitByID)
r.Put("/{id}", habitHandlers.UpdateHabit)
r.Delete("/{id}", habitHandlers.ArchiveHabit)
r.Get("/{id}/entries", habitHandlers.GetHabitEntries)
r.Post("/{id}/mark", habitHandlers.MarkHabit)
r.Delete("/{id}/entries/{date}", habitHandlers.UnmarkHabit)
})
r.Route("/api/v1/stats", func(r chi.Router) {
r.Use(AuthMiddleware(jwtService))
r.Use(RateLimitByUser(jwtService, 100, 1*time.Minute))
r.Get("/habits/{id}", statsHandlers.GetHabitStats)
})
r.Route("/api/v1/users", func(r chi.Router) {
r.Use(AuthMiddleware(jwtService))
r.Use(RateLimitByUser(jwtService, 100, 1*time.Minute))
r.Delete("/me", userHandlers.DeleteAccount)
})
r.Route("/api/v1/export", func(r chi.Router) {
r.Use(AuthMiddleware(jwtService))
r.Use(RateLimitByUser(jwtService, 1, 1*time.Hour))
r.Get("/", exportHandlers.ExportData)
})
r.Route("/api/v1/sync", func(r chi.Router) {
r.Use(AuthMiddleware(jwtService))
r.Use(RateLimitByUser(jwtService, 100, 1*time.Minute))
r.Get("/changes", syncHandlers.GetSyncChanges)
r.Post("/batch", syncHandlers.ApplySyncBatch)
})
return r
}