role_api.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package services
  2. import (
  3. "Medical_ERP/common/global"
  4. db "Medical_ERP/common/initialize"
  5. "Medical_ERP/common/redis"
  6. "Medical_ERP/dto"
  7. "Medical_ERP/models"
  8. "github.com/beego/beego/v2/core/logs"
  9. "time"
  10. )
  11. type RoleApi struct {
  12. }
  13. func (svc *RoleApi) UpdateRoleApi(d *dto.RoleApiUpdateReq) error {
  14. var err error
  15. tx := db.DB.Begin()
  16. // 删除之前的角色关联的api
  17. result := db.DB.Where("role_key = ?", d.RoleKey).Delete(&RoleApi{})
  18. if result.RowsAffected == 1 {
  19. tx.Rollback()
  20. logs.Error("delete api list error, %s", result.Error)
  21. return global.UpdateFailedErr
  22. }
  23. var roleApiList []models.RoleApi
  24. // 添加新增的角色关联的api
  25. for _, v := range d.ApiList {
  26. roleApiObj := models.RoleApi{}
  27. roleApiObj.SetApi(v.ServiceId, v.Name, v.Path, v.Action, d.RoleKey)
  28. roleApiObj.SetCreateBy(d.UpdateBy)
  29. roleApiList = append(roleApiList, roleApiObj)
  30. }
  31. // 批量插入
  32. err = tx.Create(&roleApiList).Error
  33. if err != nil {
  34. tx.Rollback()
  35. logs.Error("save api list error, %s", err)
  36. return global.UpdateFailedErr
  37. }
  38. tx.Commit()
  39. // 更新redis
  40. redis.SetJson(global.RedisPrefixRoleApi, roleApiList, 24*time.Hour)
  41. return nil
  42. }
  43. func (svc *RoleApi) GetRoleApi(roleKey string) ([]models.RoleApi, error) {
  44. var roleApiList []models.RoleApi
  45. err := redis.GetJson(global.RedisPrefixRoleApi+roleKey, &roleApiList)
  46. if err != nil {
  47. logs.Error("get role api list from redis error, %s", err)
  48. }
  49. err = db.DB.Where("role_key = ?", roleKey).Find(&roleApiList).Error
  50. if err != nil {
  51. logs.Error("get role api list error, %s", err)
  52. return roleApiList, err
  53. }
  54. // 更新redis
  55. redis.SetJson(global.RedisPrefixRoleApi+roleKey, roleApiList, 24*time.Hour)
  56. return roleApiList, err
  57. }