Initial
This commit is contained in:
39
app/lib/helpers/factory.go
Normal file
39
app/lib/helpers/factory.go
Normal 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user