1Panel/backend/app/service/group.go

90 lines
2.4 KiB
Go
Raw Normal View History

package service
import (
"github.com/1Panel-dev/1Panel/backend/app/dto"
"github.com/1Panel-dev/1Panel/backend/constant"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
)
type GroupService struct{}
type IGroupService interface {
2022-08-31 23:16:10 +08:00
GetGroupInfo(id uint) (*dto.GroupInfo, error)
List(req dto.GroupSearch) ([]dto.GroupInfo, error)
Create(groupDto dto.GroupOperate) error
Update(id uint, name string) error
Delete(id uint) error
}
func NewIGroupService() IGroupService {
return &GroupService{}
}
2022-08-31 23:16:10 +08:00
func (u *GroupService) GetGroupInfo(id uint) (*dto.GroupInfo, error) {
group, err := groupRepo.Get(commonRepo.WithByID(id))
if err != nil {
return nil, constant.ErrRecordNotFound
}
2022-08-31 23:16:10 +08:00
var dtoGroup dto.GroupInfo
if err := copier.Copy(&dtoGroup, &group); err != nil {
return nil, errors.WithMessage(constant.ErrStructTransform, err.Error())
}
return &dtoGroup, err
}
func (u *GroupService) List(req dto.GroupSearch) ([]dto.GroupInfo, error) {
groups, err := groupRepo.GetList(groupRepo.WithByType(req.Type))
if err != nil {
return nil, constant.ErrRecordNotFound
}
var dtoUsers []dto.GroupInfo
for _, group := range groups {
var item dto.GroupInfo
if err := copier.Copy(&item, &group); err != nil {
return nil, errors.WithMessage(constant.ErrStructTransform, err.Error())
}
dtoUsers = append(dtoUsers, item)
}
return dtoUsers, err
}
2022-08-31 23:16:10 +08:00
func (u *GroupService) Create(groupDto dto.GroupOperate) error {
group, _ := groupRepo.Get(commonRepo.WithByName(groupDto.Name), commonRepo.WithByName(groupDto.Name))
if group.ID != 0 {
return constant.ErrRecordExist
}
if err := copier.Copy(&group, &groupDto); err != nil {
return errors.WithMessage(constant.ErrStructTransform, err.Error())
}
if err := groupRepo.Create(&group); err != nil {
return err
}
return nil
}
2022-08-31 23:16:10 +08:00
func (u *GroupService) Delete(id uint) error {
group, _ := groupRepo.Get(commonRepo.WithByID(id))
if group.ID == 0 {
return constant.ErrRecordNotFound
}
2022-08-31 23:16:10 +08:00
if err := hostRepo.ChangeGroup(group.Name, "default"); err != nil {
return err
}
return groupRepo.Delete(commonRepo.WithByID(id))
}
2022-08-31 23:16:10 +08:00
func (u *GroupService) Update(id uint, name string) error {
group, _ := groupRepo.Get(commonRepo.WithByID(id))
if group.ID == 0 {
return constant.ErrRecordNotFound
}
upMap := make(map[string]interface{})
upMap["name"] = name
if err := hostRepo.ChangeGroup(group.Name, name); err != nil {
return err
}
return groupRepo.Update(id, upMap)
}