classlib/ExpenseTracker.Application/Accounts/Commands/Update/UpdateAccountCommandHandler.cs
2024-08-07 21:12:02 +03:00

46 lines
1.4 KiB
C#

using AutoMapper;
using MediatR;
using ExpenseTracker.Application.Common.Exceptions;
using ExpenseTracker.Application.Common.Interfaces;
using ExpenseTracker.Domain.Entities;
namespace ExpenseTracker.Application.Accounts.Commands.Update;
public class UpdateAccountCommandHandler : IRequestHandler<UpdateAccountCommand, AccountDto>
{
private readonly IMapper _mapper;
private readonly IUnitOfWork _unitOfWork;
public UpdateAccountCommandHandler(IMapper mapper, IUnitOfWork unitOfWork)
{
_mapper = mapper;
_unitOfWork = unitOfWork;
}
public async Task<AccountDto> Handle(UpdateAccountCommand request, CancellationToken cancellationToken)
{
var databaseEntity = _unitOfWork.AccountRepository.Queryable.FirstOrDefault(e => e.Id == request.Id);
if (databaseEntity == null)
{
throw new NotFoundException();
}
// TODO: Add UserId validation. Throw NotFoundException when there is no user with given UserId
var updatedEntity = new Account()
{
Id = request.Id,
Name = request.Name ?? databaseEntity.Name,
Description = request.Description,
UserId = request.UserId
};
databaseEntity = await _unitOfWork.AccountRepository.UpdateOneAsync(updatedEntity, cancellationToken);
await _unitOfWork.SaveAsync(cancellationToken);
return _mapper.Map<AccountDto>(databaseEntity);
}
}