27 lines
654 B
Go

package models
import (
"math/rand"
"time"
"github.com/oklog/ulid/v2"
"gorm.io/gorm"
)
type EntityBase struct {
ID ulid.ULID `gorm:"type:uuid;primaryKey"`
CreatedAt time.Time `gorm:"index"`
UpdatedAt time.Time `gorm:"index"`
DeletedAt gorm.DeletedAt `gorm:"index"`
}
// BeforeCreate is called by GORM before creating a record
func (eb *EntityBase) BeforeCreate(tx *gorm.DB) error {
if eb.ID.Compare(ulid.ULID{}) == 0 { // If ID is empty
// Generate a new ULID
entropy := ulid.Monotonic(rand.New(rand.NewSource(time.Now().UnixNano())), 0)
eb.ID = ulid.MustNew(ulid.Timestamp(time.Now()), entropy)
}
return nil
}