diff --git a/cmd/http-server/main.go b/cmd/http-server/main.go index 240af3f..c06440a 100644 --- a/cmd/http-server/main.go +++ b/cmd/http-server/main.go @@ -1,11 +1,14 @@ package main import ( + "fmt" + "os" "time" "github.com/swaggo/files" "github.com/swaggo/gin-swagger" + "git.qowevisa.me/Qowevisa/fin-check-api/db" docs "git.qowevisa.me/Qowevisa/fin-check-api/docs" "git.qowevisa.me/Qowevisa/fin-check-api/handlers" "git.qowevisa.me/Qowevisa/fin-check-api/middleware" @@ -29,6 +32,10 @@ import ( // @host gonapi.qowevisa.click // @BasePath /api func main() { + if err := db.Init(); err != nil { + fmt.Printf("ERROR: db.Init: %v\n", err) + os.Exit(1) + } r := gin.Default() docs.SwaggerInfo.BasePath = "/api" r.Use(cors.New(cors.Config{ diff --git a/db/db.go b/db/db.go index fe704a6..2e116e9 100644 --- a/db/db.go +++ b/db/db.go @@ -2,6 +2,7 @@ package db import ( "errors" + "fmt" "log" "os" "sync" @@ -19,6 +20,15 @@ var ( ERROR_DB_NOT_INIT = errors.New("Database connection is not initialized") ) +func Init() error { + dbc := Connect() + // Seeds + if err := initStateOfDb(dbc); err != nil { + return fmt.Errorf("initStateOfDb: %w", err) + } + return nil +} + func Connect() *gorm.DB { conMu.Lock() defer conMu.Unlock() @@ -62,3 +72,45 @@ func Connect() *gorm.DB { gormDB.AutoMigrate(&Metric{}) return newUDB } + +var ( + CANT_FIND_METRIC = errors.New("Can't find proper metrics in database") +) + +func initMetrics(tx *gorm.DB) error { + var metrics []Metric + if err := tx.Find(&metrics).Error; err != nil { + return err + } + metricsThatNeeded := []*Metric{ + &Metric{Name: "None", Short: "pcs", Value: 0}, + &Metric{Name: "Gram", Short: "g", Value: 1}, + &Metric{Name: "Kilogram", Short: "kg", Value: 2}, + &Metric{Name: "Liter", Short: "l", Value: 3}, + } + if len(metrics) == 0 { + for _, m := range metricsThatNeeded { + if err := tx.Create(m).Error; err != nil { + return err + } + } + return nil + } + for _, m := range metricsThatNeeded { + tmp := &Metric{} + if err := tx.Find(tmp, m).Error; err != nil { + return err + } + if tmp.ID == 0 { + return CANT_FIND_METRIC + } + } + return nil +} + +func initStateOfDb(tx *gorm.DB) error { + if err := initMetrics(tx); err != nil { + return fmt.Errorf("initMetrics: %w", err) + } + return nil +}