| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- using AutoMapper;
- using BlackRock.Reporting.API.Core;
- using BlackRock.Reporting.API.Models;
- using MediatR;
-
- namespace BlackRock.Reporting.API.Mediator
- {
- public class DeleteUsersCommand : IRequest<Result<Guid>>
- {
- public Guid Id { get; }
- public DeleteUsersCommand(Guid id)
- {
- this.Id = id;
- }
- }
-
- public class DeleteUsersCommandHandlers : IRequestHandler<DeleteUsersCommand, Result<Guid>>
- {
- private readonly ILogger<DeleteUsersCommandHandlers> logger;
- private readonly IMapper mapper;
- private readonly IUsersRepository repository;
- private readonly IUnitOfWork unitOfWork;
- public DeleteUsersCommandHandlers(ILogger<DeleteUsersCommandHandlers> logger, IMapper mapper, IUsersRepository repository, IUnitOfWork unitOfWork)
- {
- this.unitOfWork = unitOfWork;
- this.repository = repository;
- this.mapper = mapper;
- this.logger = logger;
- }
- public async Task<Result<Guid>> Handle(DeleteUsersCommand command, CancellationToken cancellationToken)
- {
- if (command.Id == Guid.Empty)
- throw new ArgumentException($"Parameter {nameof(command.Id)} must not be null or empty");
- logger.LogInformation("Deleting user ...");
- try
- {
- var user = await repository.GetByIdAsync(command.Id);
- repository.Remove(user);
- await unitOfWork.SaveChangesAsync();
- logger.LogInformation($"User with id {user.Id} has been deleted successfully");
- return new Result<Guid> { Data = command.Id };
- }
- catch (Exception ex)
- {
- return new Result<Guid> { IsSuccess = false, Error = "Faild to delete data from DB." };
- }
- }
- }
- }
|