Базово работает
gRPC на отдельном порту
This commit is contained in:
83
.vscode/launch.json
vendored
83
.vscode/launch.json
vendored
@@ -1,51 +1,34 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
// Use IntelliSense to find out which attributes exist for C# debugging
|
||||
// Use hover for the description of the existing attributes
|
||||
// For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md
|
||||
"name": ".NET Core Launch (console)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceFolder}/src/Console/bin/Debug/net10.0/Console.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}/src/Console",
|
||||
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
|
||||
"console": "internalConsole",
|
||||
"stopAtEntry": false
|
||||
},
|
||||
{
|
||||
"name": ".NET Core Attach",
|
||||
"type": "coreclr",
|
||||
"request": "attach"
|
||||
},
|
||||
{
|
||||
// Use IntelliSense to find out which attributes exist for C# debugging
|
||||
// Use hover for the description of the existing attributes
|
||||
// For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md.
|
||||
"name": ".NET Core Launch (web)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceFolder}/src/ApiServer/bin/Debug/net10.0/ApiServer.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}/src/ApiServer",
|
||||
"stopAtEntry": false,
|
||||
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
|
||||
"serverReadyAction": {
|
||||
"action": "openExternally",
|
||||
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
|
||||
},
|
||||
"env": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"sourceFileMap": {
|
||||
"/Views": "${workspaceFolder}/Views"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "ApiServer",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build ApiServer",
|
||||
"program": "${workspaceFolder}/src/ApiServer/bin/Debug/net10.0/ApiServer.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}/src/ApiServer",
|
||||
"stopAtEntry": false,
|
||||
"env": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Console",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build Console",
|
||||
"program": "dotnet",
|
||||
"args": [
|
||||
"run",
|
||||
"--no-build",
|
||||
"--project",
|
||||
"${workspaceFolder}/src/Console/Console.csproj"
|
||||
],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "integratedTerminal",
|
||||
"stopAtEntry": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
58
.vscode/tasks.json
vendored
58
.vscode/tasks.json
vendored
@@ -1,41 +1,19 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "build",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"build",
|
||||
"${workspaceFolder}/src/ApiServer/ApiServer.csproj",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary;ForceNoAlign"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "publish",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/src/ApiServer/ApiServer.csproj",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary;ForceNoAlign"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "watch",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"watch",
|
||||
"run",
|
||||
"--project",
|
||||
"${workspaceFolder}/src/ApiServer/ApiServer.csproj"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
}
|
||||
]
|
||||
}
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "build ApiServer",
|
||||
"type": "shell",
|
||||
"command": "dotnet build ${workspaceFolder}/src/ApiServer/ApiServer.csproj",
|
||||
"group": "build",
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "build Console",
|
||||
"type": "shell",
|
||||
"command": "dotnet build ${workspaceFolder}/src/Console/Console.csproj",
|
||||
"group": "build",
|
||||
"problemMatcher": "$msCompile"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
40
scripts/restart-db.sh
Executable file
40
scripts/restart-db.sh
Executable file
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
CONTAINER_NAME="sms-postgres"
|
||||
VOLUME_NAME="sms-postgres-data"
|
||||
IMAGE="postgres:16"
|
||||
PORT="5432"
|
||||
POSTGRES_USER="sms"
|
||||
POSTGRES_PASSWORD="sms"
|
||||
POSTGRES_DB="sms_task"
|
||||
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "docker не найден. Установите Docker и повторите." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Останавливаю и удаляю контейнер ${CONTAINER_NAME}..."
|
||||
docker rm -f "${CONTAINER_NAME}" >/dev/null 2>&1 || true
|
||||
|
||||
echo "Удаляю том ${VOLUME_NAME}..."
|
||||
docker volume rm "${VOLUME_NAME}" >/dev/null 2>&1 || true
|
||||
|
||||
echo "Запускаю PostgreSQL (${IMAGE})..."
|
||||
docker run -d \
|
||||
--name "${CONTAINER_NAME}" \
|
||||
-e POSTGRES_USER="${POSTGRES_USER}" \
|
||||
-e POSTGRES_PASSWORD="${POSTGRES_PASSWORD}" \
|
||||
-e POSTGRES_DB="${POSTGRES_DB}" \
|
||||
-p "${PORT}:5432" \
|
||||
-v "${VOLUME_NAME}:/var/lib/postgresql/data" \
|
||||
"${IMAGE}" >/dev/null
|
||||
|
||||
echo "Готово."
|
||||
echo " Host: localhost:${PORT}"
|
||||
echo " Database: ${POSTGRES_DB}"
|
||||
echo " User: ${POSTGRES_USER}"
|
||||
echo " Password: ${POSTGRES_PASSWORD}"
|
||||
echo ""
|
||||
echo "Connection string:"
|
||||
echo " Host=localhost;Port=${PORT};Database=${POSTGRES_DB};Username=${POSTGRES_USER};Password=${POSTGRES_PASSWORD}"
|
||||
@@ -15,7 +15,19 @@ public sealed class GrpcSmsClient : ISmsClient, IDisposable
|
||||
|
||||
public GrpcSmsClient(GrpcSmsClientOptions options)
|
||||
{
|
||||
_channel = GrpcChannel.ForAddress(options.Address);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -58,14 +70,12 @@ public sealed class GrpcSmsClient : ISmsClient, IDisposable
|
||||
_channel.Dispose();
|
||||
}
|
||||
|
||||
private static Dish ToDish(MenuItem item) => new()
|
||||
{
|
||||
Id = item.Id,
|
||||
Article = item.Article,
|
||||
Name = item.Name,
|
||||
Price = (decimal)item.Price,
|
||||
IsWeighted = item.IsWeighted,
|
||||
FullPath = item.FullPath,
|
||||
Barcodes = item.Barcodes.ToList(),
|
||||
};
|
||||
private static Dish ToDish(MenuItem item) => new(
|
||||
item.Id,
|
||||
item.Article,
|
||||
item.Name,
|
||||
(decimal)item.Price,
|
||||
item.IsWeighted,
|
||||
item.FullPath,
|
||||
item.Barcodes.ToList());
|
||||
}
|
||||
|
||||
@@ -2,5 +2,5 @@ namespace ApiClient.Grpc;
|
||||
|
||||
public sealed class GrpcSmsClientOptions
|
||||
{
|
||||
public string Address { get; set; } = "http://localhost:5053";
|
||||
public string Address { get; set; } = "http://localhost:5054";
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ public sealed class HttpSmsClient : ISmsClient, IDisposable
|
||||
{
|
||||
var request = new GetMenuApiRequest
|
||||
{
|
||||
CommandParameters = new GetMenuParameters { WithPrice = withPrice },
|
||||
CommandParameters = new GetMenuParameters(withPrice),
|
||||
};
|
||||
|
||||
var response = await SendAsync(request, cancellationToken);
|
||||
@@ -38,11 +38,9 @@ public sealed class HttpSmsClient : ISmsClient, IDisposable
|
||||
{
|
||||
var request = new SendOrderApiRequest
|
||||
{
|
||||
CommandParameters = new SendOrderParameters
|
||||
{
|
||||
OrderId = order.Id.ToString(),
|
||||
MenuItems = order.Items.ToList(),
|
||||
},
|
||||
CommandParameters = new SendOrderParameters(
|
||||
order.Id.ToString(),
|
||||
order.Items.ToList()),
|
||||
};
|
||||
|
||||
var response = await SendAsync(request, cancellationToken);
|
||||
@@ -53,7 +51,7 @@ public sealed class HttpSmsClient : ISmsClient, IDisposable
|
||||
|
||||
private async Task<ApiResponse> SendAsync(ApiRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(request, ApiJsonOptions.Instance);
|
||||
var json = JsonSerializer.Serialize(request, request.GetType(), ApiJsonOptions.Instance);
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
using var httpResponse = await _httpClient.PostAsync("/", content, cancellationToken);
|
||||
|
||||
|
||||
@@ -19,9 +19,18 @@ public static class DependencyInjection
|
||||
services.AddSingleton<IMenuStore, InMemoryMenuStore>();
|
||||
services.AddSingleton<ISmsApiService, SmsApiService>();
|
||||
|
||||
services.AddControllers()
|
||||
.AddJsonOptions(options =>
|
||||
{
|
||||
options.JsonSerializerOptions.PropertyNamingPolicy = Contracts.ApiJsonOptions.Instance.PropertyNamingPolicy;
|
||||
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
|
||||
options.JsonSerializerOptions.Converters.Add(new DecimalFromStringJsonConverter());
|
||||
});
|
||||
|
||||
services.ConfigureHttpJsonOptions(options =>
|
||||
{
|
||||
options.SerializerOptions.PropertyNamingPolicy = Contracts.ApiJsonOptions.Instance.PropertyNamingPolicy;
|
||||
options.SerializerOptions.PropertyNameCaseInsensitive = true;
|
||||
options.SerializerOptions.Converters.Add(new DecimalFromStringJsonConverter());
|
||||
});
|
||||
|
||||
|
||||
@@ -5,16 +5,8 @@ namespace ApiServer.Mapping;
|
||||
|
||||
internal static class MenuMapper
|
||||
{
|
||||
public static Dish ApplyPriceVisibility(Dish dish, bool withPrice) => new()
|
||||
{
|
||||
Id = dish.Id,
|
||||
Article = dish.Article,
|
||||
Name = dish.Name,
|
||||
Price = withPrice ? dish.Price : 0,
|
||||
IsWeighted = dish.IsWeighted,
|
||||
FullPath = dish.FullPath,
|
||||
Barcodes = dish.Barcodes,
|
||||
};
|
||||
public static Dish ApplyPriceVisibility(Dish dish, bool withPrice) =>
|
||||
dish with { Price = withPrice ? dish.Price : 0 };
|
||||
|
||||
public static MenuItem ToGrpc(Dish dish, bool withPrice) => new()
|
||||
{
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
using ApiServer;
|
||||
using ApiServer.Grpc;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// REST — HTTP/1.1; gRPC (h2c) — отдельный порт с HTTP/2 (без TLS нельзя смешать на одном порту).
|
||||
builder.WebHost.ConfigureKestrel(options =>
|
||||
{
|
||||
options.ListenLocalhost(5053, listen => listen.Protocols = HttpProtocols.Http1);
|
||||
options.ListenLocalhost(5054, listen => listen.Protocols = HttpProtocols.Http2);
|
||||
});
|
||||
|
||||
builder.Services.AddApiServer(builder.Configuration);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddGrpc();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5053",
|
||||
"applicationUrl": "http://localhost:5053;http://localhost:5054",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7193;http://localhost:5053",
|
||||
"applicationUrl": "https://localhost:7193;http://localhost:5053;http://localhost:5054",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
|
||||
@@ -6,26 +6,22 @@ internal sealed class InMemoryMenuStore : IMenuStore
|
||||
{
|
||||
private readonly List<Dish> _menu =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Id = "5979224",
|
||||
Article = "A1004292",
|
||||
Name = "Каша гречневая",
|
||||
Price = 50,
|
||||
IsWeighted = false,
|
||||
FullPath = @"ПРОИЗВОДСТВО\Гарниры",
|
||||
Barcodes = ["57890975627974236429"],
|
||||
},
|
||||
new()
|
||||
{
|
||||
Id = "9084246",
|
||||
Article = "A1004293",
|
||||
Name = "Конфеты Коровка",
|
||||
Price = 300,
|
||||
IsWeighted = true,
|
||||
FullPath = @"ДЕСЕРТЫ\Развес",
|
||||
Barcodes = [],
|
||||
},
|
||||
new(
|
||||
"5979224",
|
||||
"A1004292",
|
||||
"Каша гречневая",
|
||||
50,
|
||||
false,
|
||||
@"ПРОИЗВОДСТВО\Гарниры",
|
||||
["57890975627974236429"]),
|
||||
new(
|
||||
"9084246",
|
||||
"A1004293",
|
||||
"Конфеты Коровка",
|
||||
300,
|
||||
true,
|
||||
@"ДЕСЕРТЫ\Развес",
|
||||
[]),
|
||||
];
|
||||
|
||||
private readonly HashSet<string> _orderIds = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
@@ -1,10 +1,37 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>ConsoleApp</RootNamespace>
|
||||
<AssemblyName>Sms.Console</AssemblyName>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ApiClient\ApiClient.csproj" />
|
||||
<ProjectReference Include="..\Domain\Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="EFCore.NamingConventions" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.8">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.8" />
|
||||
<PackageReference Include="Npgsql" Version="10.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
19
src/Console/Data/AppDbContext.cs
Normal file
19
src/Console/Data/AppDbContext.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ConsoleApp.Data;
|
||||
|
||||
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<MenuDish> Dishes => Set<MenuDish>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<MenuDish>(entity =>
|
||||
{
|
||||
entity.ToTable("dishes");
|
||||
entity.Property(d => d.Barcodes)
|
||||
.HasColumnType("jsonb")
|
||||
.HasConversion(BarcodesJsonConverter.Instance);
|
||||
});
|
||||
}
|
||||
}
|
||||
21
src/Console/Data/AppDbContextFactory.cs
Normal file
21
src/Console/Data/AppDbContextFactory.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace ConsoleApp.Data;
|
||||
|
||||
internal sealed class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
|
||||
{
|
||||
public AppDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json")
|
||||
.Build();
|
||||
|
||||
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
|
||||
optionsBuilder.UseNpgsql(configuration.GetConnectionString("Default"))
|
||||
.UseSnakeCaseNamingConvention();
|
||||
return new AppDbContext(optionsBuilder.Options);
|
||||
}
|
||||
}
|
||||
19
src/Console/Data/BarcodesJsonConverter.cs
Normal file
19
src/Console/Data/BarcodesJsonConverter.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
namespace ConsoleApp.Data;
|
||||
|
||||
internal static class BarcodesJsonConverter
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new();
|
||||
|
||||
public static ValueConverter<List<string>, string> Instance { get; } = new(
|
||||
v => Serialize(v),
|
||||
v => Deserialize(v));
|
||||
|
||||
private static string Serialize(List<string> value) =>
|
||||
JsonSerializer.Serialize(value, JsonOptions);
|
||||
|
||||
private static List<string> Deserialize(string value) =>
|
||||
JsonSerializer.Deserialize<List<string>>(value, JsonOptions) ?? [];
|
||||
}
|
||||
43
src/Console/Data/DatabaseInitializer.cs
Normal file
43
src/Console/Data/DatabaseInitializer.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Npgsql;
|
||||
|
||||
namespace ConsoleApp.Data;
|
||||
|
||||
internal sealed class DatabaseInitializer(AppDbContext db, IConfiguration configuration)
|
||||
{
|
||||
public async Task InitializeAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString("Default")
|
||||
?? throw new InvalidOperationException("Connection string 'Default' не задана.");
|
||||
|
||||
await EnsureDatabaseExistsAsync(connectionString, cancellationToken);
|
||||
await db.Database.MigrateAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken)
|
||||
{
|
||||
var builder = new NpgsqlConnectionStringBuilder(connectionString);
|
||||
var databaseName = builder.Database
|
||||
?? throw new InvalidOperationException("Имя базы данных не указано в строке подключения.");
|
||||
|
||||
builder.Database = "postgres";
|
||||
|
||||
await using var connection = new NpgsqlConnection(builder.ConnectionString);
|
||||
await connection.OpenAsync(cancellationToken);
|
||||
|
||||
await using var checkCommand = connection.CreateCommand();
|
||||
checkCommand.CommandText = "SELECT 1 FROM pg_database WHERE datname = @name";
|
||||
checkCommand.Parameters.AddWithValue("name", databaseName);
|
||||
|
||||
var exists = await checkCommand.ExecuteScalarAsync(cancellationToken) is not null;
|
||||
if (exists)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var createCommand = connection.CreateCommand();
|
||||
createCommand.CommandText = $"CREATE DATABASE \"{databaseName.Replace("\"", "\"\"")}\"";
|
||||
await createCommand.ExecuteNonQueryAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
25
src/Console/Data/DishRepository.cs
Normal file
25
src/Console/Data/DishRepository.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
using Domain.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ConsoleApp.Data;
|
||||
|
||||
internal sealed class DishRepository(AppDbContext db)
|
||||
{
|
||||
public async Task SaveAsync(IReadOnlyList<Dish> dishes, CancellationToken cancellationToken)
|
||||
{
|
||||
await db.Dishes.ExecuteDeleteAsync(cancellationToken);
|
||||
db.Dishes.AddRange(dishes.Select(ToEntity));
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private static MenuDish ToEntity(Dish dish) => new()
|
||||
{
|
||||
Id = dish.Id,
|
||||
Article = dish.Article,
|
||||
Name = dish.Name,
|
||||
Price = dish.Price,
|
||||
IsWeighted = dish.IsWeighted,
|
||||
FullPath = dish.FullPath,
|
||||
Barcodes = dish.Barcodes.ToList(),
|
||||
};
|
||||
}
|
||||
18
src/Console/Data/MenuDish.cs
Normal file
18
src/Console/Data/MenuDish.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace ConsoleApp.Data;
|
||||
|
||||
public sealed class MenuDish
|
||||
{
|
||||
public string Id { get; set; } = "";
|
||||
|
||||
public string Article { get; set; } = "";
|
||||
|
||||
public string Name { get; set; } = "";
|
||||
|
||||
public decimal Price { get; set; }
|
||||
|
||||
public bool IsWeighted { get; set; }
|
||||
|
||||
public string FullPath { get; set; } = "";
|
||||
|
||||
public List<string> Barcodes { get; set; } = [];
|
||||
}
|
||||
34
src/Console/DependencyInjection.cs
Normal file
34
src/Console/DependencyInjection.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using ApiClient;
|
||||
using ApiClient.Grpc;
|
||||
using ApiClient.Http;
|
||||
using ConsoleApp.Data;
|
||||
using ConsoleApp.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace ConsoleApp;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IServiceCollection AddConsoleApp(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddDbContext<AppDbContext>(options =>
|
||||
options.UseNpgsql(configuration.GetConnectionString("Default"))
|
||||
.UseSnakeCaseNamingConvention());
|
||||
|
||||
services.AddScoped<DatabaseInitializer>();
|
||||
services.AddScoped<DishRepository>();
|
||||
services.AddScoped<ConsoleAppRunner>();
|
||||
|
||||
services.AddSingleton<ISmsClient>(sp =>
|
||||
{
|
||||
var backend = configuration["ApiClient:Backend"] ?? "Http";
|
||||
return backend.Equals("Grpc", StringComparison.OrdinalIgnoreCase)
|
||||
? SmsClientFactory.CreateGrpc(configuration.GetSection("Grpc").Get<GrpcSmsClientOptions>() ?? new())
|
||||
: SmsClientFactory.CreateHttp(configuration.GetSection("Http").Get<HttpSmsClientOptions>() ?? new());
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
52
src/Console/Logging/ConsoleLog.cs
Normal file
52
src/Console/Logging/ConsoleLog.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
namespace ConsoleApp.Logging;
|
||||
|
||||
internal sealed class TeeTextWriter(TextWriter consoleWriter, TextWriter logWriter) : TextWriter
|
||||
{
|
||||
public override System.Text.Encoding Encoding => consoleWriter.Encoding;
|
||||
|
||||
public override void Write(char value)
|
||||
{
|
||||
consoleWriter.Write(value);
|
||||
logWriter.Write(value);
|
||||
}
|
||||
|
||||
public override void Write(string? value)
|
||||
{
|
||||
consoleWriter.Write(value);
|
||||
logWriter.Write(value);
|
||||
}
|
||||
|
||||
public override void WriteLine(string? value)
|
||||
{
|
||||
consoleWriter.WriteLine(value);
|
||||
logWriter.WriteLine(value);
|
||||
}
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
consoleWriter.Flush();
|
||||
logWriter.Flush();
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
logWriter.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
internal static class ConsoleLog
|
||||
{
|
||||
public static IDisposable Configure()
|
||||
{
|
||||
var logPath = $"test-sms-console-app-{DateTime.Now:yyyyMMdd}.log";
|
||||
var logWriter = new StreamWriter(logPath, append: true) { AutoFlush = true };
|
||||
var tee = new TeeTextWriter(global::System.Console.Out, logWriter);
|
||||
global::System.Console.SetOut(tee);
|
||||
return logWriter;
|
||||
}
|
||||
}
|
||||
69
src/Console/Migrations/20260601135443_Init.Designer.cs
generated
Normal file
69
src/Console/Migrations/20260601135443_Init.Designer.cs
generated
Normal file
@@ -0,0 +1,69 @@
|
||||
// <auto-generated />
|
||||
using ConsoleApp.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ConsoleApp.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260601135443_Init")]
|
||||
partial class Init
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("ConsoleApp.Data.MenuDish", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Article")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("article");
|
||||
|
||||
b.Property<string>("Barcodes")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("barcodes");
|
||||
|
||||
b.Property<string>("FullPath")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("full_path");
|
||||
|
||||
b.Property<bool>("IsWeighted")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_weighted");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<decimal>("Price")
|
||||
.HasColumnType("numeric")
|
||||
.HasColumnName("price");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_dishes");
|
||||
|
||||
b.ToTable("dishes", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
38
src/Console/Migrations/20260601135443_Init.cs
Normal file
38
src/Console/Migrations/20260601135443_Init.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ConsoleApp.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class Init : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "dishes",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<string>(type: "text", nullable: false),
|
||||
article = table.Column<string>(type: "text", nullable: false),
|
||||
name = table.Column<string>(type: "text", nullable: false),
|
||||
price = table.Column<decimal>(type: "numeric", nullable: false),
|
||||
is_weighted = table.Column<bool>(type: "boolean", nullable: false),
|
||||
full_path = table.Column<string>(type: "text", nullable: false),
|
||||
barcodes = table.Column<string>(type: "jsonb", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_dishes", x => x.id);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "dishes");
|
||||
}
|
||||
}
|
||||
}
|
||||
66
src/Console/Migrations/AppDbContextModelSnapshot.cs
Normal file
66
src/Console/Migrations/AppDbContextModelSnapshot.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
// <auto-generated />
|
||||
using ConsoleApp.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ConsoleApp.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
partial class AppDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("ConsoleApp.Data.MenuDish", b =>
|
||||
{
|
||||
b.Property<string>("Id")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Article")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("article");
|
||||
|
||||
b.Property<string>("Barcodes")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("barcodes");
|
||||
|
||||
b.Property<string>("FullPath")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("full_path");
|
||||
|
||||
b.Property<bool>("IsWeighted")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_weighted");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<decimal>("Price")
|
||||
.HasColumnType("numeric")
|
||||
.HasColumnName("price");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_dishes");
|
||||
|
||||
b.ToTable("dishes", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,21 @@
|
||||
// See https://aka.ms/new-console-template for more information
|
||||
Console.WriteLine("Hello, World!");
|
||||
using ConsoleApp;
|
||||
using ConsoleApp.Logging;
|
||||
using ConsoleApp.Services;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(AppContext.BaseDirectory)
|
||||
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
|
||||
.AddEnvironmentVariables()
|
||||
.Build();
|
||||
|
||||
using var _ = ConsoleLog.Configure();
|
||||
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IConfiguration>(configuration);
|
||||
services.AddConsoleApp(configuration);
|
||||
|
||||
await using var provider = services.BuildServiceProvider();
|
||||
await using var scope = provider.CreateAsyncScope();
|
||||
await scope.ServiceProvider.GetRequiredService<ConsoleAppRunner>().RunAsync(CancellationToken.None);
|
||||
|
||||
96
src/Console/Services/ConsoleAppRunner.cs
Normal file
96
src/Console/Services/ConsoleAppRunner.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
using ApiClient;
|
||||
using ConsoleApp.Data;
|
||||
using Domain.Entities;
|
||||
|
||||
namespace ConsoleApp.Services;
|
||||
|
||||
internal sealed class ConsoleAppRunner(
|
||||
DatabaseInitializer databaseInitializer,
|
||||
DishRepository dishRepository,
|
||||
ISmsClient smsClient)
|
||||
{
|
||||
public async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Console.WriteLine("Инициализация базы данных...");
|
||||
await databaseInitializer.InitializeAsync(cancellationToken);
|
||||
Console.WriteLine("База данных готова.");
|
||||
|
||||
Console.WriteLine("Запрос меню с сервера...");
|
||||
var menuResponse = await smsClient.GetMenuAsync(withPrice: true, cancellationToken);
|
||||
|
||||
if (!menuResponse.Success)
|
||||
{
|
||||
Console.WriteLine(menuResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
var dishes = menuResponse.Data?.MenuItems ?? [];
|
||||
await dishRepository.SaveAsync(dishes, cancellationToken);
|
||||
|
||||
Console.WriteLine("Меню:");
|
||||
foreach (var dish in dishes)
|
||||
{
|
||||
Console.WriteLine(dish);
|
||||
}
|
||||
|
||||
var order = await ReadOrderAsync(dishes, cancellationToken);
|
||||
if (order is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Console.WriteLine(order);
|
||||
Console.WriteLine("Отправка заказа на сервер...");
|
||||
var sendResponse = await smsClient.SendOrderAsync(order, cancellationToken);
|
||||
|
||||
if (sendResponse.Success)
|
||||
{
|
||||
Console.WriteLine("УСПЕХ");
|
||||
return;
|
||||
}
|
||||
|
||||
Console.WriteLine(sendResponse);
|
||||
}
|
||||
|
||||
private static Task<Order?> ReadOrderAsync(IReadOnlyList<Dish> dishes, CancellationToken cancellationToken)
|
||||
{
|
||||
var dishesByArticle = dishes.ToDictionary(d => d.Article, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Введите позиции заказа в формате Код:Количество;Код:Количество;...");
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
Console.Write("> ");
|
||||
var input = Console.ReadLine();
|
||||
|
||||
if (!OrderInputParser.TryParse(input, out var lines, out var parseError))
|
||||
{
|
||||
Console.WriteLine(parseError);
|
||||
continue;
|
||||
}
|
||||
|
||||
var unknownArticles = lines
|
||||
.Select(line => line.Article)
|
||||
.Where(article => !dishesByArticle.ContainsKey(article))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
if (unknownArticles.Count > 0)
|
||||
{
|
||||
Console.WriteLine($"Неизвестные коды: {string.Join(", ", unknownArticles)}");
|
||||
continue;
|
||||
}
|
||||
|
||||
Order order = new();
|
||||
foreach (var (article, quantity) in lines)
|
||||
{
|
||||
order = order.AddItem(dishesByArticle[article].Id, quantity);
|
||||
}
|
||||
|
||||
return Task.FromResult<Order?>(order);
|
||||
}
|
||||
|
||||
return Task.FromResult<Order?>(null);
|
||||
}
|
||||
}
|
||||
56
src/Console/Services/OrderInputParser.cs
Normal file
56
src/Console/Services/OrderInputParser.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace ConsoleApp.Services;
|
||||
|
||||
internal static class OrderInputParser
|
||||
{
|
||||
public static bool TryParse(
|
||||
string? input,
|
||||
out List<(string Article, decimal Quantity)> items,
|
||||
out string errorMessage)
|
||||
{
|
||||
items = [];
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
errorMessage = "Строка заказа не может быть пустой.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var parts = input.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
foreach (var part in parts)
|
||||
{
|
||||
var pair = part.Split(':', 2);
|
||||
if (pair.Length != 2)
|
||||
{
|
||||
errorMessage = $"Некорректный формат позиции: '{part}'. Ожидается Код:Количество.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var article = pair[0].Trim();
|
||||
if (string.IsNullOrWhiteSpace(article))
|
||||
{
|
||||
errorMessage = "Артикул не может быть пустым.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!decimal.TryParse(pair[1].Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var quantity)
|
||||
&& !decimal.TryParse(pair[1].Trim(), NumberStyles.Number, CultureInfo.CurrentCulture, out quantity))
|
||||
{
|
||||
errorMessage = $"Некорректное количество для артикула '{article}'.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (quantity <= 0)
|
||||
{
|
||||
errorMessage = $"Количество для артикула '{article}' должно быть больше нуля.";
|
||||
return false;
|
||||
}
|
||||
|
||||
items.Add((article, quantity));
|
||||
}
|
||||
|
||||
errorMessage = "";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
16
src/Console/appsettings.json
Normal file
16
src/Console/appsettings.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"Default": "Host=localhost;Port=5432;Database=sms_task;Username=sms;Password=sms"
|
||||
},
|
||||
"ApiClient": {
|
||||
"Backend": "Grpc"
|
||||
},
|
||||
"Http": {
|
||||
"BaseUrl": "http://localhost:5053",
|
||||
"Username": "user",
|
||||
"Password": "password"
|
||||
},
|
||||
"Grpc": {
|
||||
"Address": "http://localhost:5054"
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ public static class ApiJsonOptions
|
||||
var options = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = null,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
};
|
||||
|
||||
options.Converters.Add(new DecimalFromStringJsonConverter());
|
||||
|
||||
@@ -2,7 +2,13 @@ using Domain.Entities;
|
||||
|
||||
namespace Contracts.Menu;
|
||||
|
||||
public sealed class GetMenuData
|
||||
public sealed record GetMenuData(IReadOnlyList<Dish> MenuItems)
|
||||
{
|
||||
public IReadOnlyList<Dish> MenuItems { get; init; } = [];
|
||||
public GetMenuData()
|
||||
: this([])
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() =>
|
||||
string.Join(Environment.NewLine, MenuItems);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Contracts.Menu;
|
||||
|
||||
public sealed class GetMenuParameters
|
||||
public sealed record GetMenuParameters(bool WithPrice = true)
|
||||
{
|
||||
public bool WithPrice { get; set; } = true;
|
||||
public override string ToString() => $"WithPrice={WithPrice}";
|
||||
}
|
||||
|
||||
@@ -2,9 +2,13 @@ using Domain.Entities;
|
||||
|
||||
namespace Contracts.Orders;
|
||||
|
||||
public sealed class SendOrderParameters
|
||||
public sealed record SendOrderParameters(string OrderId, IReadOnlyList<OrderItem> MenuItems)
|
||||
{
|
||||
public required string OrderId { get; init; }
|
||||
public SendOrderParameters(string OrderId)
|
||||
: this(OrderId, [])
|
||||
{
|
||||
}
|
||||
|
||||
public IReadOnlyList<OrderItem> MenuItems { get; init; } = [];
|
||||
public override string ToString() =>
|
||||
$"OrderId={OrderId}, Items=[{string.Join("; ", MenuItems)}]";
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
namespace Contracts.Requests;
|
||||
|
||||
public class ApiRequest
|
||||
public record ApiRequest
|
||||
{
|
||||
public string Command { get; set; } = "";
|
||||
public string Command { get; init; } = "";
|
||||
|
||||
public override string ToString() => Command;
|
||||
}
|
||||
|
||||
public class ApiRequest<TParameters> : ApiRequest
|
||||
public record ApiRequest<TParameters> : ApiRequest
|
||||
{
|
||||
public TParameters? CommandParameters { get; set; }
|
||||
public TParameters? CommandParameters { get; init; }
|
||||
|
||||
public override string ToString() =>
|
||||
CommandParameters is null ? Command : $"{Command} ({CommandParameters})";
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ using Contracts.Menu;
|
||||
|
||||
namespace Contracts.Requests;
|
||||
|
||||
public sealed class GetMenuApiRequest : ApiRequest<GetMenuParameters>
|
||||
public sealed record GetMenuApiRequest : ApiRequest<GetMenuParameters>
|
||||
{
|
||||
public GetMenuApiRequest()
|
||||
{
|
||||
|
||||
@@ -2,7 +2,7 @@ using Contracts.Orders;
|
||||
|
||||
namespace Contracts.Requests;
|
||||
|
||||
public sealed class SendOrderApiRequest : ApiRequest<SendOrderParameters>
|
||||
public sealed record SendOrderApiRequest : ApiRequest<SendOrderParameters>
|
||||
{
|
||||
public SendOrderApiRequest()
|
||||
{
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
namespace Contracts.Responses;
|
||||
|
||||
public class ApiResponse
|
||||
public record ApiResponse
|
||||
{
|
||||
public required string Command { get; init; }
|
||||
|
||||
public bool Success { get; init; }
|
||||
|
||||
public string ErrorMessage { get; init; } = "";
|
||||
|
||||
public override string ToString() =>
|
||||
Success ? $"{Command}: OK" : $"{Command}: {ErrorMessage}";
|
||||
}
|
||||
|
||||
@@ -18,16 +18,33 @@ public static class ApiResponseDeserializer
|
||||
|
||||
public static ApiResponse Deserialize(JsonElement json)
|
||||
{
|
||||
if (!json.TryGetProperty("Command", out var commandElement))
|
||||
if (!TryGetCommand(json, out var command))
|
||||
{
|
||||
return json.Deserialize<ApiResponse>(ApiJsonOptions.Instance)!;
|
||||
}
|
||||
|
||||
return commandElement.GetString() switch
|
||||
return command switch
|
||||
{
|
||||
Commands.GetMenu => json.Deserialize<GetMenuApiResponse>(ApiJsonOptions.Instance)!,
|
||||
Commands.SendOrder => json.Deserialize<SendOrderApiResponse>(ApiJsonOptions.Instance)!,
|
||||
_ => json.Deserialize<ApiResponse>(ApiJsonOptions.Instance)!,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool TryGetCommand(JsonElement json, out string? command)
|
||||
{
|
||||
foreach (var property in json.EnumerateObject())
|
||||
{
|
||||
if (!property.Name.Equals("Command", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
command = property.Value.GetString();
|
||||
return true;
|
||||
}
|
||||
|
||||
command = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ using Contracts.Menu;
|
||||
|
||||
namespace Contracts.Responses;
|
||||
|
||||
public sealed class GetMenuApiResponse : ApiResponse
|
||||
public sealed record GetMenuApiResponse : ApiResponse
|
||||
{
|
||||
public GetMenuData? Data { get; init; }
|
||||
|
||||
public override string ToString() =>
|
||||
Data is null ? base.ToString() : $"{base.ToString()}{Environment.NewLine}{Data}";
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
namespace Contracts.Responses;
|
||||
|
||||
public sealed class SendOrderApiResponse : ApiResponse;
|
||||
|
||||
public sealed record SendOrderApiResponse : ApiResponse;
|
||||
|
||||
Reference in New Issue
Block a user