-
I have a base model with a hook like this: type Model struct {
Id string `json:"id" gorm:"type:uuid;primary_key"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
} Then I introduced a tag for encryption/hashing, when the tag is set, the column should get encrypted in beforeSave and decrypted in afterFind. But when I add beforeSave to my base model, I cannot reflect the original model, because it only uses the base model. Example: type User struct {
Model
Username string `json:"username" gorm:"primaryKey;not null"`
Password string `json:"-" gorm:"not null"`
Totp string `json:"-" gorm:"not null" protect:"encrypt"`
BackupCode string `json:"-" gorm:"not null" protect:"encrypt"`
}
// Addition to the base Model:
func (m *Model) BeforeSave(_ *gorm.DB) error {
v := reflect.ValueOf(i)
for i := 0; i < v.NumField(); i++ {
// only fields of Model are available
}
return nil
} The thing i would need, is a global hook at my database object... something like func main() {
db, err := gorm.Open(sqlite.Open("test.sqlite"), &gorm.Config{})
if err != nil {
panic(err)
}
beforeSave := func (model *interface{}) {
// Action here
}
db.BeforeSave(beforeSave)
err = db.AutoMigrate(&models.User{})
if err != nil {
panic(err)
}
db.Create(&models.User{
Username: "DreamTexX",
Password: "123",
Totp: "test totp",
BackupCode: "test backup code",
})
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Just discovered callbacks, using them now |
Beta Was this translation helpful? Give feedback.
Just discovered callbacks, using them now