90a96b4125
- Remove api_es service, Dockerfile, all Go source files - Remove api_es from docker-compose.yml, nginx-ssl.conf, .env, Makefile - Replace nginx /api/ proxy with /api/v1/ → api_yal:8787 - Add amenity/upload domains, AuthResponse, GET /auth/me, GET /objects/my to api_yal - Rewrite easysite frontend: types, composables, and all 5 pages to use api_yal DTOs - Wire nuxt.config public.apiBase, add useObjects CRUD composable - Update docs references from api_es to api_yal
68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
package database
|
|
|
|
import (
|
|
"api_yal/internal/config"
|
|
"api_yal/internal/models"
|
|
"api_yal/internal/logger"
|
|
"fmt"
|
|
|
|
"go.uber.org/zap"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func NewPostgresConnection(cfg *config.Config) (*gorm.DB, error) {
|
|
zapLogger := logger.Get()
|
|
zapLogger.Info("Start connect to Postgres DB")
|
|
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=UTC",
|
|
cfg.DBHost, cfg.DBUser, cfg.DBPassword, cfg.DBName, cfg.DBPort)
|
|
zapLogger.Info("dsn = %s", zap.String("dsn", dsn))
|
|
|
|
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
|
}
|
|
|
|
zapLogger.Info("AutoMigrate models")
|
|
// Автомиграция
|
|
if err := autoMigrate(db); err != nil {
|
|
zapLogger.Error("can't migrate models, error = %s", zap.Error(err))
|
|
return nil, fmt.Errorf("can't migrate models, error = %s", err)
|
|
}
|
|
zapLogger.Info("Migrate complite successfully")
|
|
|
|
zapLogger.Info("Fill init data")
|
|
|
|
zapLogger.Info("Successfully connected to database")
|
|
return db, nil
|
|
}
|
|
|
|
func autoMigrate(db *gorm.DB) error {
|
|
zapLogger := logger.Get()
|
|
zapLogger.Debug("Start migration")
|
|
models := []interface{}{
|
|
&models.Account{},
|
|
&models.UpdateHistory{},
|
|
&models.Object{},
|
|
&models.ObjectImage{},
|
|
&models.Amenity{},
|
|
&models.RatingVote{},
|
|
&models.VoteBreakdown{},
|
|
&models.Rating{},
|
|
&models.Feedback{},
|
|
&models.Comment{},
|
|
&models.Appeal{},
|
|
&models.AppealHistory{},
|
|
&models.PasswordReset{},
|
|
}
|
|
|
|
for _, model := range models {
|
|
if err := db.AutoMigrate(model); err != nil {
|
|
return fmt.Errorf("failed to migrate %T: %w", model, err)
|
|
}
|
|
}
|
|
|
|
zapLogger.Debug("End migration seccessfully")
|
|
return nil
|
|
}
|