Core.Blueprint.BFF/Core.Blueprint.API/Controllers/BaseController.cs
Sergio Matias Urquin 37db76d94a remove old packages
2025-05-17 23:05:46 -06:00

48 lines
1.8 KiB
C#

using Lib.Architecture.BuildingBlocks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Refit;
namespace Core.Blueprint.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BaseController(ILogger<BaseController> logger) : ControllerBase
{
private readonly ILogger<BaseController> _logger = logger;
protected Guid TrackingId => (Guid)(HttpContext.Items["TrackingId"] ?? Guid.NewGuid());
protected async Task<IActionResult> Handle<T>(Func<Task<ApiResponse<T>>> apiCall) where T : class
{
var response = await apiCall().ConfigureAwait(false);
_logger.LogInformation($"{TrackingId} - {response.RequestMessage?.Method} {response.RequestMessage?.RequestUri} - Status: {response.StatusCode}");
return FromAPIResponse(response);
}
private IActionResult FromAPIResponse<T>(ApiResponse<T> response) where T : class
{
if (response.IsSuccessful)
return StatusCode((int)response.StatusCode, response.Content);
else
{
dynamic errorContent = string.Empty;
try
{
errorContent = JsonConvert.DeserializeObject<string>(response.Error?.Content ?? string.Empty) ?? string.Empty;
}
catch (Exception)
{
errorContent = JsonConvert.DeserializeObject<HttpError>(response.Error?.Content);
if (errorContent?.Error?.ErrorCode is null && errorContent?.Error?.Message is null && errorContent?.Error?.Target is null)
errorContent = JsonConvert.DeserializeObject<GenericErrorResponse>(response.Error?.Content);
}
return StatusCode((int)response.StatusCode, errorContent);
}
}
}
}