Skip to content

Modern Docker Management, Designed for Everyone

refactor: use uuid as ID in base model

Kyle Mendell082d4eff58f4
diff --git a/backend/internal/models/base.go b/backend/internal/models/base.go
index 0f9e762ea..b89dbe6c1 100644
--- a/backend/internal/models/base.go
+++ b/backend/internal/models/base.go
@@ -4,7 +4,11 @@ import (
"database/sql/driver"
"encoding/json"
"fmt"
+ "reflect"
"time"
+
+ "github.com/google/uuid"
+ "gorm.io/gorm"
)
// Base model with common fields
@@ -13,6 +17,24 @@ type BaseModel struct {
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
}
+// Ensure a UUID is set on the parent model's `ID` field before create
+func (m *BaseModel) BeforeCreate(tx *gorm.DB) (err error) {
+ v := tx.Statement.ReflectValue
+ if v.Kind() == reflect.Ptr {
+ v = v.Elem()
+ }
+ if v.IsValid() && v.Kind() == reflect.Struct {
+ f := v.FieldByName("ID")
+ if f.IsValid() && f.CanSet() && f.Kind() == reflect.String && f.Len() == 0 {
+ f.SetString(uuid.New().String())
+ }
+ }
+ if m.CreatedAt.IsZero() {
+ m.CreatedAt = time.Now()
+ }
+ return nil
+}
+
// JSON type for handling JSON columns
type JSON map[string]interface{}