You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UpdateUserEmailCommand.cs 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using AutoMapper;
  2. using BlackRock.Reporting.API.Mediator.UserMediator.Dto;
  3. using BlackRock.Reporting.API.Mediator.UserMediator.Model;
  4. using BlackRock.Reporting.API.Core.Interfaces;
  5. using BlackRock.Reporting.API.Core.Models;
  6. using MediatR;
  7. namespace BlackRock.Reporting.API.Mediator.UserMediator.Commands
  8. {
  9. public class UpdateUserEmailCommand : IRequest<Result<UserDto>>
  10. {
  11. public UserCommand User { set; get; }
  12. public int Id { get; set; }
  13. }
  14. public class UpdateUserEmailCommandHandlers : IRequestHandler<UpdateUserEmailCommand, Result<UserDto>>
  15. {
  16. private readonly ILogger<UpdateUserEmailCommandHandlers> logger;
  17. private readonly IMapper mapper;
  18. private readonly IUnitOfWork unitOfWork;
  19. public UpdateUserEmailCommandHandlers(ILogger<UpdateUserEmailCommandHandlers> logger, IMapper mapper, IUnitOfWork unitOfWork)
  20. {
  21. this.unitOfWork = unitOfWork;
  22. this.mapper = mapper;
  23. this.logger = logger;
  24. }
  25. public async Task<Result<UserDto>> Handle(UpdateUserEmailCommand command, CancellationToken cancellationToken)
  26. {
  27. if (command.Id <= 0)
  28. throw new ArgumentException($"Parameter {nameof(command.Id)} must not be grater than 0");
  29. logger.LogInformation("Updating user email ...");
  30. try
  31. {
  32. var user = await unitOfWork.UsersRepository.GetByIdAsync(command.Id);
  33. unitOfWork.UsersRepository.UpdateEmail(user, command.User.Email);
  34. await unitOfWork.SaveChangesAsync();
  35. var updatedUser = mapper.Map<User, UserDto>(user);
  36. logger.LogInformation($"Email of the user with id {user.Id} has been updated successfully");
  37. return new Result<UserDto> { Data = updatedUser };
  38. }
  39. catch (Exception ex)
  40. {
  41. return new Result<UserDto> { IsSuccess = false, Error = "Faild to update data in DB." };
  42. }
  43. }
  44. }
  45. }