You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
2.9 KiB
76 lines
2.9 KiB
using CoreAgent.Domain.Models.Common;
|
|
using MediatR;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Extensions.Logging;
|
|
using System.Net;
|
|
|
|
namespace CoreAgent.API.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("api/v{version:apiVersion}/[controller]")]
|
|
public abstract class BaseApiController : ControllerBase
|
|
{
|
|
protected readonly IMediator _mediator;
|
|
protected readonly ILogger<BaseApiController> _logger;
|
|
|
|
protected BaseApiController(IMediator mediator, ILogger<BaseApiController> logger)
|
|
{
|
|
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
protected async Task<IActionResult> HandleRequest<TRequest, TResponse>(TRequest request)
|
|
where TRequest : IRequest<TResponse>
|
|
{
|
|
try
|
|
{
|
|
_logger.LogInformation("Handling request of type {RequestType}", typeof(TRequest).Name);
|
|
var response = await _mediator.Send(request);
|
|
return ApiActionResult<TResponse>.Ok(response);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return HandleException<TResponse>(ex);
|
|
}
|
|
}
|
|
|
|
protected async Task<IActionResult> HandleRequest<TRequest>(TRequest request)
|
|
where TRequest : IRequest
|
|
{
|
|
try
|
|
{
|
|
_logger.LogInformation("Handling request of type {RequestType}", typeof(TRequest).Name);
|
|
await _mediator.Send(request);
|
|
return ApiActionResult.Ok();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return HandleException(ex);
|
|
}
|
|
}
|
|
|
|
private IActionResult HandleException<T>(Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error handling request");
|
|
return ApiActionResult<T>.Error(ex.Message, "INTERNAL_ERROR", HttpStatusCode.InternalServerError);
|
|
}
|
|
|
|
private IActionResult HandleException(Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error handling request");
|
|
return ApiActionResult.Error(ex.Message, "INTERNAL_ERROR", HttpStatusCode.InternalServerError);
|
|
}
|
|
|
|
protected IActionResult Success<T>(T data, string message = null) =>
|
|
ApiActionResult<T>.Ok(data, message);
|
|
|
|
protected IActionResult Success(string message = null) =>
|
|
ApiActionResult.Ok(message);
|
|
|
|
protected IActionResult Error(string message, string errorCode = "ERROR", HttpStatusCode statusCode = HttpStatusCode.BadRequest) =>
|
|
ApiActionResult.Error(message, errorCode, statusCode);
|
|
|
|
protected IActionResult Error<T>(string message, string errorCode = "ERROR", HttpStatusCode statusCode = HttpStatusCode.BadRequest) =>
|
|
ApiActionResult<T>.Error(message, errorCode, statusCode);
|
|
}
|
|
}
|