Add db seeding with default metrics for users

This commit is contained in:
qowevisa 2024-11-19 10:13:02 +02:00
parent 06b317511d
commit 8855cc3e54
2 changed files with 59 additions and 0 deletions

View File

@ -1,11 +1,14 @@
package main package main
import ( import (
"fmt"
"os"
"time" "time"
"github.com/swaggo/files" "github.com/swaggo/files"
"github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger"
"git.qowevisa.me/Qowevisa/fin-check-api/db"
docs "git.qowevisa.me/Qowevisa/fin-check-api/docs" docs "git.qowevisa.me/Qowevisa/fin-check-api/docs"
"git.qowevisa.me/Qowevisa/fin-check-api/handlers" "git.qowevisa.me/Qowevisa/fin-check-api/handlers"
"git.qowevisa.me/Qowevisa/fin-check-api/middleware" "git.qowevisa.me/Qowevisa/fin-check-api/middleware"
@ -29,6 +32,10 @@ import (
// @host gonapi.qowevisa.click // @host gonapi.qowevisa.click
// @BasePath /api // @BasePath /api
func main() { func main() {
if err := db.Init(); err != nil {
fmt.Printf("ERROR: db.Init: %v\n", err)
os.Exit(1)
}
r := gin.Default() r := gin.Default()
docs.SwaggerInfo.BasePath = "/api" docs.SwaggerInfo.BasePath = "/api"
r.Use(cors.New(cors.Config{ r.Use(cors.New(cors.Config{

View File

@ -2,6 +2,7 @@ package db
import ( import (
"errors" "errors"
"fmt"
"log" "log"
"os" "os"
"sync" "sync"
@ -19,6 +20,15 @@ var (
ERROR_DB_NOT_INIT = errors.New("Database connection is not initialized") 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 { func Connect() *gorm.DB {
conMu.Lock() conMu.Lock()
defer conMu.Unlock() defer conMu.Unlock()
@ -62,3 +72,45 @@ func Connect() *gorm.DB {
gormDB.AutoMigrate(&Metric{}) gormDB.AutoMigrate(&Metric{})
return newUDB 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
}