You've already forked openaccounting-server
forked from cybercinch/openaccounting-server
46 lines
898 B
Go
46 lines
898 B
Go
|
|
package models
|
||
|
|
|
||
|
|
import (
|
||
|
|
"github.com/google/uuid"
|
||
|
|
"github.com/openaccounting/oa-server/core/util/id"
|
||
|
|
"gorm.io/gorm"
|
||
|
|
)
|
||
|
|
|
||
|
|
type Base struct {
|
||
|
|
ID []byte `gorm:"type:BINARY(16);primaryKey"`
|
||
|
|
}
|
||
|
|
|
||
|
|
// GetUUID converts binary ID to UUID
|
||
|
|
func (b *Base) GetUUID() (uuid.UUID, error) {
|
||
|
|
return id.ToUUID(b.ID)
|
||
|
|
}
|
||
|
|
|
||
|
|
// GetIDString returns string representation of the ID
|
||
|
|
func (b *Base) GetIDString() string {
|
||
|
|
return id.String(b.ID)
|
||
|
|
}
|
||
|
|
|
||
|
|
// SetIDFromString parses string UUID into binary ID
|
||
|
|
func (b *Base) SetIDFromString(s string) error {
|
||
|
|
binID, err := id.FromString(s)
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
b.ID = binID
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// ValidateID checks if the ID is a valid UUID
|
||
|
|
func (b *Base) ValidateID() error {
|
||
|
|
_, err := uuid.FromBytes(b.ID)
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
|
||
|
|
// BeforeCreate GORM hook to set ID if empty
|
||
|
|
func (b *Base) BeforeCreate(tx *gorm.DB) error {
|
||
|
|
if len(b.ID) == 0 {
|
||
|
|
b.ID = id.New()
|
||
|
|
}
|
||
|
|
return nil
|
||
|
|
}
|