refactor: separate app run

This commit is contained in:
2026-05-23 14:13:49 +03:00
parent c41cbc3c2f
commit 2ca5e7fa8c
+17 -10
View File
@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
standartlog "log" standartlog "log"
"net" "net"
"os"
hubdir "github.com/lorsanstand/HomeOps-Hub/hub/internal" hubdir "github.com/lorsanstand/HomeOps-Hub/hub/internal"
"github.com/lorsanstand/HomeOps-Hub/hub/internal/migrator" "github.com/lorsanstand/HomeOps-Hub/hub/internal/migrator"
@@ -41,7 +42,7 @@ func (a *App) Run() {
DBConn, err := sql.Open("sqlite", "database.db") DBConn, err := sql.Open("sqlite", "database.db")
if err != nil { if err != nil {
a.log.Error().Err(err).Msg("failed to connect to the database") a.log.Error().Err(err).Msg("failed to connect to the database")
return os.Exit(1)
} }
defer func() { defer func() {
@@ -50,16 +51,10 @@ func (a *App) Run() {
} }
}() }()
mgrt, err := migrator.NewMigrator(hubdir.MigrationsFS, "migrations")
if err != nil {
a.log.Error().Err(err).Msg("failed to create migrator")
return
}
a.log.Info().Msg("applying database migrations") a.log.Info().Msg("applying database migrations")
if err = mgrt.ApplyMigrations(DBConn); err != nil { if err := applyMigrations(DBConn); err != nil {
a.log.Error().Err(err).Msg("migrations failed to apply") a.log.Error().Err(err).Msg("")
return os.Exit(1)
} }
a.log.Info().Msg("migrations applied successfully") a.log.Info().Msg("migrations applied successfully")
@@ -69,6 +64,7 @@ func (a *App) Run() {
connManger := connection_manager.NewConnectionManager(hubStore, statusNotifier, a.log) connManger := connection_manager.NewConnectionManager(hubStore, statusNotifier, a.log)
a.log.Info().Msg("starting hub service") a.log.Info().Msg("starting hub service")
err = a.hubServe(hubService, connManger) err = a.hubServe(hubService, connManger)
if err != nil { if err != nil {
a.log.Error().Err(err).Msg("hub service failed to start") a.log.Error().Err(err).Msg("hub service failed to start")
@@ -97,3 +93,14 @@ func (a *App) hubServe(hubService *hub_service.HubService, manager *connection_m
return nil return nil
} }
func applyMigrations(db *sql.DB) error {
mgrt, err := migrator.NewMigrator(hubdir.MigrationsFS, "migrations")
if err != nil {
return fmt.Errorf("failed to create migrator: %w", err)
}
if err = mgrt.ApplyMigrations(db); err != nil {
return fmt.Errorf("migrations failed to apply: %w", err)
}
return nil
}