| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- using AutoMapper;
- using BlackRock.Reporting.API.Core;
- using BlackRock.Reporting.API.Models;
- using MediatR;
-
- namespace BlackRock.Reporting.API.Mediator
- {
- public class UpdateAllUsersCommand : IRequest<Result<UserDto>>
- {
- public UserForm User { get; }
- public Guid Id { get; }
- public UpdateAllUsersCommand(Guid id, UserForm user)
- {
- this.Id = id;
- this.User = user;
- }
- }
-
- public class UpdateAllUsersCommandHandlers : IRequestHandler<UpdateAllUsersCommand, Result<UserDto>>
- {
- private readonly ILogger<UpdateAllUsersCommandHandlers> logger;
- private readonly IMapper mapper;
- private readonly IUsersRepository repository;
- private readonly IUnitOfWork unitOfWork;
- public UpdateAllUsersCommandHandlers(ILogger<UpdateAllUsersCommandHandlers> logger, IMapper mapper, IUsersRepository repository, IUnitOfWork unitOfWork)
- {
- this.unitOfWork = unitOfWork;
- this.repository = repository;
- this.mapper = mapper;
- this.logger = logger;
- }
- public async Task<Result<UserDto>> Handle(UpdateAllUsersCommand command, CancellationToken cancellationToken)
- {
- if (command.Id == Guid.Empty)
- throw new ArgumentException($"Parameter {nameof(command.Id)} must not be null or empty");
- logger.LogInformation("Updating user ...");
- try
- {
- var user = await repository.GetByIdAsync(command.Id);
- mapper.Map<UserForm, User>(command.User, 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." };
- }
- }
- }
- }
|