aides-repo-api/internal/app/app.go
Maxim Slipenko e4f9743dea
Some checks failed
Format and Lint / format-check (push) Failing after 2s
Format and Lint / test (push) Successful in 52s
chore: change code.alt-gnome to code.aides.space
2025-01-07 17:54:16 +03:00

140 lines
2.7 KiB
Go

package app
import (
"fmt"
"net/http"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"moul.io/zapgorm2"
"code.aides.space/aides-infra/aides-repo-api/internal/config"
"code.aides.space/aides-infra/aides-repo-api/internal/controllers/taskcontroller"
"code.aides.space/aides-infra/aides-repo-api/internal/logger"
"code.aides.space/aides-infra/aides-repo-api/internal/models"
"code.aides.space/aides-infra/aides-repo-api/internal/router"
"code.aides.space/aides-infra/aides-repo-api/internal/services/cronservice"
"code.aides.space/aides-infra/aides-repo-api/internal/services/reposervice"
"code.aides.space/aides-infra/aides-repo-api/internal/services/taskservice"
)
type App struct {
logger *logger.ZapLogger
db *gorm.DB
config *config.Config
repo *reposervice.Service
taskService *taskservice.Service
cron *cronservice.Service
taskController *taskcontroller.TaskController
router *router.Router
}
func New() (*App, error) {
app := App{}
app.createLogger()
app.config = config.New()
app.createDb()
app.createServices()
app.createControllers()
app.createRouter()
return &app, nil
}
func (app *App) createLogger() {
app.logger = logger.GetLogger()
}
func (app *App) createDb() {
logger := zapgorm2.New(app.logger.GetZap())
logger.LogMode(gormlogger.Info)
logger.SetAsDefault()
dsn := fmt.Sprintf(
"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
app.config.DBHost,
app.config.DBPort,
app.config.DBUser,
app.config.DBPassword,
app.config.DBName,
)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger})
if err != nil {
panic(err)
}
err = db.AutoMigrate(&models.Task{}, &models.GitRepoAltRepoTask{}, &models.RPMFile{})
if err != nil {
panic(err)
}
db.FirstOrCreate(&models.ALTRepo{
Name: "Sisyphus",
})
app.db = db
}
func (app *App) createServices() {
app.repo = reposervice.New(
app.db,
app.config,
)
app.taskService = taskservice.New(
app.db,
app.config,
)
app.cron = cronservice.New(
app.repo,
)
}
func (app *App) createControllers() {
app.taskController = taskcontroller.New(
app.taskService,
)
}
func (app *App) createRouter() {
app.router = router.New(
app.config,
app.taskController,
)
}
func (app *App) initServices() {
app.cron.SetupCronJobs()
app.cron.Start()
}
func (app *App) Init() {
app.initServices()
}
func (app *App) Run() {
app.logger.Info(
"Сервер запущен",
map[string]interface{}{
"port": app.config.Port,
},
)
err := app.repo.Update(true)
if err != nil {
panic(err)
}
err = http.ListenAndServe(
fmt.Sprintf(":%d", app.config.Port),
app.router.Setup(),
)
if err != nil {
panic(err)
}
}
func (app *App) Shutdown() {
app.cron.Shutdown()
}