package enums import ( "encoding/json" "fmt" "gorm.io/gorm" "nf-repo/internal/interfaces" "nf-repo/internal/opt" ) type Role uint8 var _ interfaces.Enum = (*Role)(nil) func (u Role) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]any{ "code": u.Code(), "value": u.Value(), "label": u.Label(), }) } const ( RoleRoot Role = 255 RoleAdmin Role = 254 RoleUser Role = 100 ) func (u Role) Code() string { switch u { case RoleRoot: return "root" case RoleAdmin: return "admin" case RoleUser: return "user" default: panic(fmt.Sprintf("unknown role: %d", u)) } } func (u Role) Label() string { switch u { case RoleRoot: return "根用户" case RoleAdmin: return "管理员" case RoleUser: return "用户" default: panic(fmt.Sprintf("unknown role: %d", u)) } } func (u Role) Value() int64 { return int64(u) } func (u Role) All() []interfaces.Enum { return []interfaces.Enum{ RoleAdmin, RoleUser, } } func (u Role) Where(db *gorm.DB) *gorm.DB { if opt.RoleMustLess { return db.Where("users.role < ?", u.Value()) } else { return db.Where("users.role <= ?", u.Value()) } }