role_service.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package user
  2. import (
  3. "errors"
  4. "github.com/astaxie/beego/logs"
  5. "github.com/astaxie/beego/orm"
  6. "nginx-ui/server/models"
  7. )
  8. type RoleService struct {
  9. }
  10. var Role = RoleService{}
  11. func (u *RoleService) List() ([]models.UserRole, error) {
  12. qs := orm.NewOrm().QueryTable(new(models.UserRole))
  13. var list []models.UserRole
  14. _, err := qs.All(&list)
  15. if err != nil {
  16. return nil, err
  17. }
  18. return list, err
  19. }
  20. func (u *RoleService) Save(body *models.UserRole) (*models.UserRole, error) {
  21. o := orm.NewOrm()
  22. _, err := models.InsertOrUpdate[models.UserRole](o, body)
  23. return body, err
  24. }
  25. func (u *RoleService) Delete(id int) error {
  26. o := orm.NewOrm()
  27. role := models.UserRole{}
  28. err := o.Read(&role)
  29. if err != nil && errors.Is(err, orm.ErrNoRows) {
  30. return nil
  31. } else if err != nil {
  32. return err
  33. }
  34. if role.RefCount > 0 {
  35. return errors.New("角色有引用资源,请先删除后再操作!")
  36. }
  37. _, err = o.Delete(&models.UserRole{Id: id})
  38. return err
  39. }
  40. func (u *RoleService) Ref(size int, role string) error {
  41. o := orm.NewOrm()
  42. _, err := o.Raw("UPDATE user_role SET ref_count=ref_count+? WHERE code=?", size, role).Exec()
  43. if err != nil {
  44. logs.Error("update role ref error", err)
  45. return err
  46. }
  47. return nil
  48. }