Files
2025-10-27 17:39:18 -04:00

61 lines
2.0 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Prefab.Web.Client.Models.Shared;
namespace Prefab.Web.Client.Services;
public interface INavMenuService
{
Task<Result<NavMenuModel>> Get(int depth, CancellationToken cancellationToken);
}
public sealed class NavMenuService : INavMenuService
{
private readonly HttpClient _httpClient;
public NavMenuService(HttpClient httpClient)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}
public async Task<Result<NavMenuModel>> Get(int depth, CancellationToken cancellationToken)
{
var normalizedDepth = Math.Clamp(depth, 1, 2);
try
{
using var response = await _httpClient.GetAsync($"/bff/nav-menu/{normalizedDepth}", cancellationToken);
var payload = await response.Content.ReadFromJsonAsync<Result<NavMenuModel>>(cancellationToken: cancellationToken);
if (payload is not null)
{
return payload;
}
if (!response.IsSuccessStatusCode)
{
var statusCode = (HttpStatusCode)response.StatusCode;
var problem = ResultProblem.Unexpected(
"Failed to load navigation menu.",
new HttpRequestException($"Navigation menu request failed with status code {(int)statusCode} ({statusCode})."),
statusCode);
return Result<NavMenuModel>.Failure(problem);
}
var emptyProblem = ResultProblem.Unexpected(
"Failed to load navigation menu.",
new InvalidOperationException("Navigation menu response body was empty."),
(HttpStatusCode)response.StatusCode);
return Result<NavMenuModel>.Failure(emptyProblem);
}
catch (Exception exception)
{
var problem = ResultProblem.Unexpected("Failed to load navigation menu.", exception);
return Result<NavMenuModel>.Failure(problem);
}
}
}