This commit is contained in:
Eden Kirin
2024-06-18 22:01:31 +02:00
commit 21dcabe180
21 changed files with 1039 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package helpers
import (
"reflect"
"gorm.io/gorm"
)
type Factory struct {
dbConn *gorm.DB
}
func NewFactory(dbConn *gorm.DB) *Factory {
return &Factory{
dbConn: dbConn,
}
}
func (f *Factory) CreateModel(model interface{}) {
if f.dbConn == nil {
panic("Factory created without db connection. Unable to create model.")
}
f.dbConn.Create(model)
}
func MergeValuesToModel(model interface{}, values map[string]any) {
st := reflect.ValueOf(model).Elem()
for key, value := range values {
field := st.FieldByName(key)
var v reflect.Value
if value != nil {
v = reflect.ValueOf(value)
} else {
v = reflect.Zero(field.Type())
}
field.Set(v)
}
}

27
app/lib/helpers/util.go Normal file
View File

@ -0,0 +1,27 @@
package helpers
import (
"encoding/json"
"time"
)
func UTCNow() time.Time {
utc, _ := time.LoadLocation("UTC")
return time.Now().In(utc)
}
// UNUSED allows unused variables to be included in Go programs
func UNUSED(x ...interface{}) {}
func StructToMap(data interface{}) (map[string]interface{}, error) {
dataBytes, err := json.Marshal(data)
if err != nil {
return nil, err
}
mapData := make(map[string]interface{})
err = json.Unmarshal(dataBytes, &mapData)
if err != nil {
return nil, err
}
return mapData, nil
}

View File

@ -0,0 +1,70 @@
package helpers
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_StructToMap(t *testing.T) {
t.Run("Convert simple struct to map", func(t *testing.T) {
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Height float32 `json:"height"`
}
user := &User{
Name: "Pero",
Age: 66,
Height: 187.6,
}
result, _ := StructToMap(user)
expected := make(map[string]interface{})
expected["name"] = "Pero"
expected["age"] = 66
expected["height"] = 187.6
assert.Equal(t, fmt.Sprintf("%v", result), fmt.Sprintf("%v", expected))
})
t.Run("Convert nested struct to map", func(t *testing.T) {
type Address struct {
City string `json:"city"`
PostalCode int `json:"postalCode"`
}
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Height float32 `json:"height"`
Address Address `json:"address"`
}
user := &User{
Name: "Pero",
Age: 66,
Height: 187.6,
Address: Address{
City: "Zagreb",
PostalCode: 10020,
},
}
result, _ := StructToMap(user)
address := make(map[string]interface{})
address["city"] = "Zagreb"
address["postalCode"] = 10020
expected := make(map[string]interface{})
expected["name"] = "Pero"
expected["age"] = 66
expected["height"] = 187.6
expected["address"] = make(map[string]interface{})
expected["address"] = address
assert.Equal(t, fmt.Sprintf("%v", result), fmt.Sprintf("%v", expected))
})
}