| | 1 | | using AutoMapper; |
| | 2 | | using FLP.Application.Requests.Bugs; |
| | 3 | | using FLP.Application.Responses.Bugs; |
| | 4 | | using FLP.Application.Validators.Bugs; |
| | 5 | | using FLP.Core.Context.Main; |
| | 6 | | using FLP.Core.Context.Shared; |
| | 7 | | using FLP.Core.Interfaces.Repository; |
| | 8 | | using MediatR; |
| | 9 | | using Microsoft.Extensions.Logging; |
| | 10 | |
|
| | 11 | | namespace FLP.Application.Handlers.Bugs; |
| | 12 | |
|
| 3 | 13 | | public class CreateBugHandler(IUnitOfWork _uow, IMapper _mapper, ILogger<CreateBugHandler> _logger) : IRequestHandler<Cr |
| | 14 | | { |
| | 15 | | public async Task<BaseResponse<GetBugByIdResponse>> Handle(CreateBugRequest request, CancellationToken cancellationT |
| 3 | 16 | | { |
| 3 | 17 | | cancellationToken.ThrowIfCancellationRequested(); |
| 3 | 18 | | _logger.LogInformation("Handling CreateBugRequest for Title: {Title}", request.Title); |
| | 19 | | // Validate the request |
| 3 | 20 | | var validator = new CreateBugValidator(); |
| 3 | 21 | | var validationResult = validator.Validate(request); |
| 3 | 22 | | if (!validationResult.IsValid) |
| 1 | 23 | | { |
| 1 | 24 | | _logger.LogWarning("Validation failed for CreateBugRequest: {Errors}", validationResult.Errors); |
| 1 | 25 | | return new BaseResponse<GetBugByIdResponse>(false,validationResult.Errors.Select(e => e.ErrorMessage)); |
| | 26 | | } |
| | 27 | |
|
| | 28 | | // Map the request to a domain entity |
| 2 | 29 | | var bug = _mapper.Map<Bug>(request); |
| 2 | 30 | | _uow.BeginTransaction(cancellationToken); |
| | 31 | | // Add the bug to the repository |
| 2 | 32 | | var addedBug = await _uow.BugRepository.AddAsync(bug, cancellationToken); |
| 1 | 33 | | await _uow.SaveChangesAsync(cancellationToken); |
| | 34 | |
|
| | 35 | | // Map the added bug to a response DTO |
| 1 | 36 | | var response = _mapper.Map<GetBugByIdResponse>(addedBug); |
| | 37 | |
|
| | 38 | | // Commit the transaction |
| 1 | 39 | | _uow.CommitTransaction(cancellationToken); |
| | 40 | |
|
| 1 | 41 | | _logger.LogInformation("Bug created successfully with ID: {Id}", response.Id); |
| | 42 | |
|
| 1 | 43 | | return new BaseResponse<GetBugByIdResponse>(response); |
| 2 | 44 | | } |
| | 45 | | } |