aeus-admin/formatter.go

82 lines
1.9 KiB
Go

package aeusadmin
import (
"context"
"fmt"
"git.nobla.cn/golang/aeus-admin/internal/logic"
"git.nobla.cn/golang/aeus/pkg/cache"
"git.nobla.cn/golang/rest"
"git.nobla.cn/golang/rest/types"
"gorm.io/gorm"
)
type Formatter struct {
db *gorm.DB
user *logic.User
department *logic.Department
role *logic.Role
menu *logic.Menu
}
func (f *Formatter) FormatUser(ctx context.Context, value, model any, scm *types.Schema) any {
if values, err := f.user.GetLabels(ctx); err == nil {
for _, row := range values {
if row.Value == value {
return fmt.Sprintf("%s(%s)", row.Label, row.Value)
}
}
}
return value
}
func (f *Formatter) FormatDepartment(ctx context.Context, value, model any, scm *types.Schema) any {
if values, err := f.department.GetLabels(ctx); err == nil {
for _, row := range values {
if row.Value == value {
return row.Label
}
}
}
return value
}
func (f *Formatter) FormatRole(ctx context.Context, value, model any, scm *types.Schema) any {
if values, err := f.role.GetLabels(ctx); err == nil {
for _, row := range values {
if row.Value == value {
return row.Label
}
}
}
return value
}
func (f *Formatter) FormatMenu(ctx context.Context, value, model any, scm *types.Schema) any {
if values, err := f.menu.GetLabels(ctx); err == nil {
for _, row := range values {
if row.Value == value {
return row.Label
}
}
}
return value
}
func (f *Formatter) Register() {
rest.DefaultFormatter.Register("user", f.FormatUser)
rest.DefaultFormatter.Register("department", f.FormatDepartment)
rest.DefaultFormatter.Register("role", f.FormatRole)
rest.DefaultFormatter.Register("menu", f.FormatMenu)
}
func NewFormatter(db *gorm.DB, ch cache.Cache) *Formatter {
return &Formatter{
db: db,
user: logic.NewUserLogic(db, ch),
department: logic.NewDepartmentLogic(db, ch),
role: logic.NewRoleLogic(db, ch),
menu: logic.NewMenuLogic(db, ch),
}
}