using AutoMapper; using BlackRock.Reporting.API.Core.Interfaces; using BlackRock.Reporting.API.Core.Models; using BlackRock.Reporting.API.Mediator.UserMediator.Model; using MediatR; namespace BlackRock.Reporting.API.Mediator.UserMediator.Commands { public class CreateUserCommand : UserCommand, IRequest> { } public class CreateUserCommandHandlers : IRequestHandler> { private readonly ILogger logger; private readonly IMapper mapper; private readonly IUnitOfWork unitOfWork; public CreateUserCommandHandlers(ILogger logger, IMapper mapper, IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; this.mapper = mapper; this.logger = logger; } public async Task> Handle(CreateUserCommand command, CancellationToken cancellationToken) { if (command is null) throw new ArgumentException($"Parameter {nameof(command)} must not be null"); try { logger.LogInformation("Creating new user ..."); var user = mapper.Map(command); await unitOfWork.UsersRepository.AddAsync(user); await unitOfWork.SaveChangesAsync(); logger.LogInformation($"User with id {user.Id} has been created successfully"); return new Result { Data = user.Id }; } catch (Exception ex) { logger.LogError(ex, "Faild to add data to DB."); return new Result { IsSuccess = false, Error = "Faild to add data to DB." }; } } } }