Adds refactoring

This commit is contained in:
BinaryAlley committed 2024-08-28 21:52:41 +03:00
1 parent 9d840db864
commit f37d06f8df
9 files changed
+109 -49

No files matched your search

@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries;
using Lumina.Presentation.Api.Common.Contracts.Books;
using Lumina.Presentation.Api.Core.Controllers.Common;
using MapsterMapper;
using Mediator;
using Microsoft.AspNetCore.Mvc;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.Books;
/// <summary>
/// Controller for managing books.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class BooksController : ApiController
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly ISender _mediator;
private readonly IMapper _mapper;
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="BooksController"/> class.
/// </summary>
/// <param name="mediator">Injecting service for mediating commands and queries.</param>
/// <param name="mapper">Injected service for mapping objects.</param>
public BooksController(ISender mediator, IMapper mapper)
{
_mediator = mediator;
_mapper = mapper;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Controller action for getting the list of all books.
/// </summary>
[HttpGet()]
public async Task<IActionResult> GetBooks()
{
var result = await _mediator.Send(new GetBooksQuery());
return result.Match(result => Ok(result), errors => Problem(errors));
}
/// <summary>
/// Controller action for adding a book.
/// </summary>
/// <param name="request">The command to add a book.</param>
[HttpPost()]
public async Task<IActionResult> AddBook(AddBookRequest request)
{
var result = await _mediator.Send(_mapper.Map<AddBookCommand>(request));
return result.Match(result => Created($"/api/v1/books/{result.Id}", result), errors => Problem(errors));
}
#endregion
}
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.Common;
/// <summary>
/// Base class for API controllers.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
public abstract class ApiController : ControllerBase
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Handles controllers errors.
/// </summary>
/// <param name="errors">The error to handle.</param>
protected internal IActionResult Problem(List<Error> errors)
{
if (errors.Count is 0) // if there are no custom errors given, return a generic problem
return Problem();
// try to make the problem type more specific
if (errors.All(error => error.Type == ErrorType.Validation))
return ValidationProblem(errors);
// here we could handle custom error types, for instance: if (errors.All(error => error.NumericType == 23)), where 23 could be "domain errors"
// share the list of errors within the scope of this HTTP request
HttpContext.Items[HttpContextItemKeys.ERRORS] = errors;
// get a HTTP error status code for the selected domain error type
return Problem(errors.First());
}
/// <summary>
/// Converts an <see cref="Error"/> to a standard problem response.
/// </summary>
/// <param name="error">The error to convert.</param>
protected internal IActionResult Problem(Error error)
{
var statusCode = error.Type switch
{
ErrorType.Conflict => StatusCodes.Status409Conflict,
ErrorType.NotFound => StatusCodes.Status404NotFound,
ErrorType.Validation => StatusCodes.Status400BadRequest,
ErrorType.Failure => StatusCodes.Status403Forbidden,
_ => StatusCodes.Status500InternalServerError,
};
// return the HTTP error status and the domain error message
return Problem(statusCode: statusCode, title: error.Type.ToString(), detail: error.Description);
}
/// <summary>
/// Converts a list of <see cref="Error"/> into a standard validation problem response.
/// </summary>
/// <param name="errors">The list of errors to convert.</param>
protected internal IActionResult ValidationProblem(List<Error> errors)
{
var modelStateDictionary = new ModelStateDictionary();
foreach (var error in errors)
modelStateDictionary.AddModelError(error.Code, error.Description);
return ValidationProblem(modelStateDictionary: modelStateDictionary, title: "One or more validation errors occurred.");
}
#endregion
}