48 lines
1.8 KiB
C#
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);
|
|
}
|
|
}
|
|
}
|
|
} |