Init
This commit is contained in:
60
Prefab.Web.Client/Services/INavMenuService.cs
Normal file
60
Prefab.Web.Client/Services/INavMenuService.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user