126 lines
3.5 KiB
C#

using AutoMapper;
using UserManagement.Application.Dtos.Incomming;
using UserManagement.Application.Dtos.Outgoing;
using UserManagement.Application.Interfaces;
using UserManagement.Domain.Entities;
using UserManagement.Infrastructure.Interfaces;
namespace UserManagement.Application.Services
{
public class RoleService : IRoleService
{
// CTOR
private readonly IRoleRepository _roleRepository;
private readonly IMapper _mapper;
public RoleService(IRoleRepository roleRepository, IMapper mapper)
{
_roleRepository = roleRepository;
_mapper = mapper;
}
// CREATE
public async Task<Role?> AddRoleAsync(CreatingRoleDto creatingRoleDto)
{
var role = _mapper.Map<Role>(creatingRoleDto);
var created = await _roleRepository.AddAsync(role);
return created;
}
// READ ALL
public async Task<IEnumerable<ReadingRoleDto>> GetAllRolesAsync()
{
var roles = await _roleRepository.GetAllAsync();
if (roles == null)
{
throw new KeyNotFoundException("Keine Rollen gefunden!");
}
var readDto = _mapper.Map<IEnumerable<ReadingRoleDto>>(roles);
return readDto;
}
// READ BY ID
public async Task<ReadingRoleDto> GetRoleByIdAsync(int id)
{
if (id <= 0)
{
throw new ArgumentException("Ungültige Id!");
}
var role = await _roleRepository.GetByIdAsync(id);
if (role == null)
{
throw new KeyNotFoundException("Rolle nicht gefunden!");
}
var readDto = _mapper.Map<ReadingRoleDto>(role);
return readDto;
}
// READ BY NAME
public async Task<ReadingRoleDto> GetRoleByNameAsync(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Ungültiger Rollenname!");
}
var role = await _roleRepository.GetByNameAsync(name);
if (role == null)
{
throw new KeyNotFoundException("Rolle nicht gefunden!");
}
var readDto = _mapper.Map<ReadingRoleDto>(role);
return readDto;
}
// UPDATE
public async Task<bool> UpdateRoleAsync(UpdatingRoleDto updatingRoleDto)
{
if (updatingRoleDto.Id <= 0)
{
throw new ArgumentException("Ungültige Id!");
}
var role = _mapper.Map<Role>(updatingRoleDto);
if (role == null)
{
throw new KeyNotFoundException("Rolle nicht gefunden!");
}
bool isUpdated = await _roleRepository.UpdateAsync(role);
return isUpdated;
}
// DELETE
public async Task<bool> DeleteRoleAsync(int id)
{
if (id <= 0)
{
throw new ArgumentException("Ungültige Id!");
}
var role = await _roleRepository.GetByIdAsync(id);
if (role == null)
{
throw new KeyNotFoundException("Rolle nicht gefunden!");
}
bool isDeleted = await _roleRepository.DeleteAsync(role);
return isDeleted;
}
}
}