| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- using AutoMapper;
- using BlackRock.Reporting.API.Core.Interfaces;
- using BlackRock.Reporting.API.Core.Models;
- using BlackRock.Reporting.API.Mediator.UserMediator.Dto;
- using BlackRock.Reporting.API.Mediator.UserMediator.Model;
- using MediatR;
-
- namespace BlackRock.Reporting.API.Mediator.UserMediator.Commands
- {
- public class UpdateUserCommand : IRequest<Result<UserDto>>
- {
- public UserCommand User { get; set; }
- public int Id { get; set; }
-
- }
-
- public class UpdateUserCommandHandlers : IRequestHandler<UpdateUserCommand, Result<UserDto>>
- {
- private readonly ILogger<UpdateUserCommandHandlers> logger;
- private readonly IMapper mapper;
- private readonly IUnitOfWork unitOfWork;
- public UpdateUserCommandHandlers(ILogger<UpdateUserCommandHandlers> logger, IMapper mapper, IUnitOfWork unitOfWork)
- {
- this.unitOfWork = unitOfWork;
- this.mapper = mapper;
- this.logger = logger;
- }
- public async Task<Result<UserDto>> Handle(UpdateUserCommand command, CancellationToken cancellationToken)
- {
- if (command.Id <= 0)
- throw new ArgumentException($"Parameter {nameof(command.Id)} must not be grater than 0");
- logger.LogInformation("Updating user ...");
- try
- {
- var user = await unitOfWork.UsersRepository.GetByIdAsync(command.Id);
- mapper.Map<UserCommand, User>(command.User, user);
- unitOfWork.UsersRepository.Update(user);
- await unitOfWork.SaveChangesAsync();
- var updatedUser = mapper.Map<User, UserDto>(user);
- logger.LogInformation($"User with id {user.Id} has been updated successfully");
- return new Result<UserDto> { Data = updatedUser };
- }
- catch (Exception ex)
- {
- return new Result<UserDto> { IsSuccess = false, Error = "Faild to update data in DB." };
- }
- }
- }
- }
|