Files
sms-task-one/src/ApiClient/Grpc/GrpcSmsClient.cs
Пытков Роман 50626c6ac6 Базово работает
gRPC на отдельном порту
2026-06-01 18:02:48 +03:00

82 lines
2.6 KiB
C#

using Contracts;
using Contracts.Menu;
using Contracts.Responses;
using Domain.Entities;
using Google.Protobuf.WellKnownTypes;
using Grpc.Net.Client;
using Sms.Test;
namespace ApiClient.Grpc;
public sealed class GrpcSmsClient : ISmsClient, IDisposable
{
private readonly GrpcChannel _channel;
private readonly SmsTestService.SmsTestServiceClient _client;
public GrpcSmsClient(GrpcSmsClientOptions options)
{
var address = options.Address;
var channelOptions = new GrpcChannelOptions();
if (address.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
{
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
channelOptions.HttpHandler = new SocketsHttpHandler
{
EnableMultipleHttp2Connections = true,
};
}
_channel = GrpcChannel.ForAddress(address, channelOptions);
_client = new SmsTestService.SmsTestServiceClient(_channel);
}
public async Task<GetMenuApiResponse> GetMenuAsync(bool withPrice = true, CancellationToken cancellationToken = default)
{
var response = await _client.GetMenuAsync(new BoolValue { Value = withPrice }, cancellationToken: cancellationToken);
return new GetMenuApiResponse
{
Command = Commands.GetMenu,
Success = response.Success,
ErrorMessage = response.ErrorMessage,
Data = response.Success
? new GetMenuData { MenuItems = response.MenuItems.Select(ToDish).ToList() }
: null,
};
}
public async Task<SendOrderApiResponse> SendOrderAsync(Domain.Entities.Order order, CancellationToken cancellationToken = default)
{
var grpcOrder = new Sms.Test.Order { Id = order.Id.ToString() };
grpcOrder.OrderItems.AddRange(order.Items.Select(item => new Sms.Test.OrderItem
{
Id = item.Id,
Quantity = (double)item.Quantity,
}));
var response = await _client.SendOrderAsync(grpcOrder, cancellationToken: cancellationToken);
return new SendOrderApiResponse
{
Command = Commands.SendOrder,
Success = response.Success,
ErrorMessage = response.ErrorMessage,
};
}
public void Dispose()
{
_channel.Dispose();
}
private static Dish ToDish(MenuItem item) => new(
item.Id,
item.Article,
item.Name,
(decimal)item.Price,
item.IsWeighted,
item.FullPath,
item.Barcodes.ToList());
}