Add db seeding with default metrics for users
This commit is contained in:
parent
06b317511d
commit
8855cc3e54
|
@ -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{
|
||||
|
|
52
db/db.go
52
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
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user