Files
prefab-page-detail/Prefab.Web.Client/Services/ProductDisplayService.cs
2025-10-27 21:39:50 -04:00

35 lines
1.3 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Prefab.Web.Client.Models.Catalog;
using Prefab.Web.Client.Models.Shared;
namespace Prefab.Web.Client.Services;
public interface IProductDisplayService
{
Task<Result<ProductDisplayModel>> Get(string slug, CancellationToken cancellationToken = default);
}
public sealed class ProductDisplayService(HttpClient httpClient) : IProductDisplayService
{
public async Task<Result<ProductDisplayModel>> Get(string slug, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(slug);
using var response = await httpClient.GetAsync(
$"/bff/catalog/products/{Uri.EscapeDataString(slug.Trim())}",
cancellationToken);
var payload = await response.Content.ReadFromJsonAsync<Result<ProductDisplayModel>>(cancellationToken: cancellationToken);
if (payload is not null)
{
return payload;
}
var statusCode = (HttpStatusCode)response.StatusCode;
var exception = new InvalidOperationException($"Response {(int)statusCode} did not contain a valid payload.");
var problem = ResultProblem.Unexpected("Failed to retrieve product.", exception, statusCode);
return Result<ProductDisplayModel>.Failure(problem);
}
}