tercul-backend/cmd/api/main.go
google-labs-jules[bot] 52101fbeda Refactor: Expose Analytics Service via GraphQL
This commit refactors the analytics service to align with the new DDD architecture and exposes it through the GraphQL API.

Key changes:
- A new `AnalyticsService` has been created in `internal/application/services` to encapsulate analytics-related business logic.
- The GraphQL resolver has been updated to use the new `AnalyticsService`, providing a clean and maintainable API.
- The old analytics service and its related files have been removed, reducing code duplication and confusion.
- The `bookmark`, `like`, and `work` services have been refactored to remove their dependencies on the old analytics repository.
- Unit tests have been added for the new `AnalyticsService`, and existing tests have been updated to reflect the refactoring.
2025-10-03 04:10:16 +00:00

165 lines
4.4 KiB
Go

package main
import (
"context"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime"
"syscall"
"tercul/internal/app"
graph "tercul/internal/adapters/graphql"
"tercul/internal/application/services"
dbsql "tercul/internal/data/sql"
"tercul/internal/platform/auth"
"tercul/internal/platform/config"
"tercul/internal/platform/db"
"tercul/internal/platform/log"
"tercul/internal/platform/search"
"time"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/pressly/goose/v3"
"github.com/weaviate/weaviate-go-client/v5/weaviate"
"gorm.io/gorm"
)
// runMigrations applies database migrations using goose.
func runMigrations(gormDB *gorm.DB) error {
sqlDB, err := gormDB.DB()
if err != nil {
return err
}
if err := goose.SetDialect("postgres"); err != nil {
return err
}
// This is brittle. A better approach might be to use an env var or config.
_, b, _, _ := runtime.Caller(0)
migrationsDir := filepath.Join(filepath.Dir(b), "../../internal/data/migrations")
log.LogInfo("Applying database migrations", log.F("directory", migrationsDir))
if err := goose.Up(sqlDB, migrationsDir); err != nil {
return err
}
log.LogInfo("Database migrations applied successfully")
return nil
}
// main is the entry point for the Tercul application.
func main() {
// Load configuration from environment variables
config.LoadConfig()
// Initialize structured logger with appropriate log level
log.SetDefaultLevel(log.InfoLevel)
log.LogInfo("Starting Tercul application",
log.F("environment", config.Cfg.Environment),
log.F("version", "1.0.0"))
// Initialize database connection
database, err := db.InitDB()
if err != nil {
log.LogFatal("Failed to initialize database", log.F("error", err))
}
defer db.Close()
if err := runMigrations(database); err != nil {
log.LogFatal("Failed to apply database migrations", log.F("error", err))
}
// Initialize Weaviate client
weaviateCfg := weaviate.Config{
Host: config.Cfg.WeaviateHost,
Scheme: config.Cfg.WeaviateScheme,
}
weaviateClient, err := weaviate.NewClient(weaviateCfg)
if err != nil {
log.LogFatal("Failed to create weaviate client", log.F("error", err))
}
// Create search client
searchClient := search.NewWeaviateWrapper(weaviateClient)
// Create repositories
repos := dbsql.NewRepositories(database)
// Create application services
analyticsSvc := services.NewAnalyticsService(
repos.Work,
repos.Translation,
repos.Author,
repos.User,
repos.Like,
)
// Create application
application := app.NewApplication(repos, searchClient, nil) // Analytics service is now separate
// Create GraphQL server
resolver := &graph.Resolver{
App: application,
AnalyticsService: analyticsSvc,
}
jwtManager := auth.NewJWTManager()
srv := NewServerWithAuth(resolver, jwtManager)
graphQLServer := &http.Server{
Addr: config.Cfg.ServerPort,
Handler: srv,
}
log.LogInfo("GraphQL server created successfully", log.F("port", config.Cfg.ServerPort))
// Create GraphQL playground
playgroundHandler := playground.Handler("GraphQL", "/query")
playgroundServer := &http.Server{
Addr: config.Cfg.PlaygroundPort,
Handler: playgroundHandler,
}
log.LogInfo("GraphQL playground created successfully", log.F("port", config.Cfg.PlaygroundPort))
// Start HTTP servers in goroutines
go func() {
log.LogInfo("Starting GraphQL server",
log.F("port", config.Cfg.ServerPort))
if err := graphQLServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.LogFatal("Failed to start GraphQL server",
log.F("error", err))
}
}()
go func() {
log.LogInfo("Starting GraphQL playground",
log.F("port", config.Cfg.PlaygroundPort))
if err := playgroundServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.LogFatal("Failed to start GraphQL playground",
log.F("error", err))
}
}()
// Wait for interrupt signal to gracefully shutdown the servers
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.LogInfo("Shutting down servers...")
// Graceful shutdown
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := graphQLServer.Shutdown(ctx); err != nil {
log.LogError("GraphQL server forced to shutdown",
log.F("error", err))
}
if err := playgroundServer.Shutdown(ctx); err != nil {
log.LogError("GraphQL playground forced to shutdown",
log.F("error", err))
}
log.LogInfo("All servers shutdown successfully")
}