Change initMetrics seeding to use new generic function and add seeding for Currencies

This commit is contained in:
qowevisa 2024-11-20 18:46:07 +02:00
parent d929492e3d
commit 33ffa6275b

View File

@ -78,40 +78,62 @@ var (
CANT_FIND_METRIC = errors.New("Can't find proper metrics in database") CANT_FIND_METRIC = errors.New("Can't find proper metrics in database")
) )
func initMetrics(tx *gorm.DB) error { func checkSeededValues[T Identifiable](whatToCheck []*T, errorIfNotFound error, tx *gorm.DB) error {
var metrics []Metric var valuesInDB []T
if err := tx.Find(&metrics).Error; err != nil { if err := tx.Find(&valuesInDB).Error; err != nil {
return err return err
} }
if len(valuesInDB) == 0 {
for _, v := range whatToCheck {
if err := tx.Create(v).Error; err != nil {
return err
}
}
return nil
}
for _, v := range whatToCheck {
var tmp T
if err := tx.Find(&tmp, v).Error; err != nil {
return err
}
if tmp.GetID() == 0 {
return errorIfNotFound
}
}
return nil
}
func initMetrics(tx *gorm.DB) error {
metricsThatNeeded := []*Metric{ metricsThatNeeded := []*Metric{
&Metric{Name: "None", Short: "pcs", Value: 0}, &Metric{Name: "None", Short: "pcs", Value: 0},
&Metric{Name: "Gram", Short: "g", Value: 1}, &Metric{Name: "Gram", Short: "g", Value: 1},
&Metric{Name: "Kilogram", Short: "kg", Value: 2}, &Metric{Name: "Kilogram", Short: "kg", Value: 2},
&Metric{Name: "Liter", Short: "l", Value: 3}, &Metric{Name: "Liter", Short: "l", Value: 3},
} }
if len(metrics) == 0 { return checkSeededValues(metricsThatNeeded, CANT_FIND_METRIC, tx)
for _, m := range metricsThatNeeded { }
if err := tx.Create(m).Error; err != nil {
return err func initCurrencies(tx *gorm.DB) error {
currsThatNeeded := []*Currency{
{Name: "Dollar", Symbol: "$", ISOName: "USD"},
{Name: "Moldavian Leu", Symbol: "L", ISOName: "MDL"},
{Name: "Romanian Leu", Symbol: "L", ISOName: "RON"},
{Name: "Polish Zloty", Symbol: "zł", ISOName: "PLN"},
{Name: "Ukrainian Hryvnia", Symbol: "₴", ISOName: "UAH"},
{Name: "Euro", Symbol: "€", ISOName: "EUR"},
{Name: "Russian Ruble", Symbol: "₽", ISOName: "RUB"},
{Name: "Kazakhstani Tenge", Symbol: "₸", ISOName: "KZT"},
{Name: "Chinese Yuan", Symbol: "¥", ISOName: "CNY"},
} }
} return checkSeededValues(currsThatNeeded, CANT_FIND_METRIC, tx)
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 { func initStateOfDb(tx *gorm.DB) error {
if err := initMetrics(tx); err != nil { if err := initMetrics(tx); err != nil {
return fmt.Errorf("initMetrics: %w", err) return fmt.Errorf("initMetrics: %w", err)
} }
if err := initCurrencies(tx); err != nil {
return fmt.Errorf("initCurrencies: %w", err)
}
return nil return nil
} }