0
0

Add API documentation

This commit is contained in:
Serghei Cebotari 2024-01-14 23:03:52 +03:00
parent 0452f379c6
commit 27dd2af627
4 changed files with 113 additions and 69 deletions

View File

@ -5,78 +5,95 @@ using System.Linq;
namespace RhSolutions.Api.Controllers namespace RhSolutions.Api.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
public class ProductsController : ControllerBase public class ProductsController : ControllerBase
{ {
private RhSolutionsContext dbContext; private RhSolutionsContext dbContext;
private IPricelistParser parser; private IPricelistParser parser;
public ProductsController(RhSolutionsContext dbContext, IPricelistParser parser) public ProductsController(RhSolutionsContext dbContext, IPricelistParser parser)
{ {
this.dbContext = dbContext; this.dbContext = dbContext;
this.parser = parser; this.parser = parser;
} }
[HttpGet] /// <summary>
public IAsyncEnumerable<Product> GetProducts() /// Возвращает все продукты в базе данных
{ /// </summary>
return dbContext.Products /// <returns></returns>
.AsAsyncEnumerable(); [HttpGet]
} public IAsyncEnumerable<Product> GetProducts()
{
return dbContext.Products
.AsAsyncEnumerable();
}
[HttpGet("{id}")] /// <summary>
public IEnumerable<Product> GetProduct(string id) /// Возвращает продукт по номеру артикула
{ /// </summary>
return dbContext.Products /// <param name="id">Номер артикула</param>
.Where(p => p.Id.Equals(id)); /// <returns></returns>
} [HttpGet("{id}")]
public IEnumerable<Product> GetProduct(string id)
{
return dbContext.Products
.Where(p => p.Id.Equals(id));
}
[HttpPost] /// <summary>
public IActionResult PostProductsFromXls() /// Загрузка прайс-листа в формате xlsx в базу данных
{ /// </summary>
try /// <returns></returns>
{ [HttpPost]
var products = parser.GetProducts(HttpContext).GroupBy(p => p.ProductSku) public IActionResult PostProductsFromXls()
.Select(g => new Product(g.Key) {
{ try
Name = g.First().Name, {
DeprecatedSkus = g.SelectMany(p => p.DeprecatedSkus).Distinct().ToList(), var products = parser.GetProducts(HttpContext).GroupBy(p => p.ProductSku)
ProductLines = g.SelectMany(p => p.ProductLines).Distinct().ToList(), .Select(g => new Product(g.Key)
IsOnWarehouse = g.Any(p => p.IsOnWarehouse == true), {
ProductMeasure = g.First().ProductMeasure, Name = g.First().Name,
DeliveryMakeUp = g.First().DeliveryMakeUp, DeprecatedSkus = g.SelectMany(p => p.DeprecatedSkus).Distinct().ToList(),
Price = g.First().Price ProductLines = g.SelectMany(p => p.ProductLines).Distinct().ToList(),
}); IsOnWarehouse = g.Any(p => p.IsOnWarehouse == true),
ProductMeasure = g.First().ProductMeasure,
DeliveryMakeUp = g.First().DeliveryMakeUp,
Price = g.First().Price
});
foreach (var p in products) foreach (var p in products)
{ {
dbContext.Add<Product>(p); dbContext.Add<Product>(p);
} }
dbContext.SaveChanges(); dbContext.SaveChanges();
return Ok(); return Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
return BadRequest(ex.Message); return BadRequest(ex.Message);
} }
} }
[HttpDelete] /// <summary>
public IActionResult DeleteAllProducts() /// Удаление всех продуктов из базы данных
{ /// </summary>
List<Product> deleted = new(); /// <returns></returns>
if (dbContext.Products.Count() > 0) [HttpDelete]
{ public IActionResult DeleteAllProducts()
foreach (Product p in dbContext.Products) {
{ List<Product> deleted = new();
deleted.Add(p); if (dbContext.Products.Count() > 0)
dbContext.Remove(p); {
} foreach (Product p in dbContext.Products)
dbContext.SaveChanges(); {
return Ok(deleted); deleted.Add(p);
} dbContext.Remove(p);
else return Ok("Empty db"); }
} dbContext.SaveChanges();
} return Ok(deleted);
}
else return Ok("Empty db");
}
}
} }

View File

@ -14,6 +14,11 @@ namespace RhSolutions.Api.Controllers
this.context = context; this.context = context;
} }
/// <summary>
/// Поиск артикула в базе данных через предварительную мультиклассовую классификацию с применением ML-модели артикулов
/// </summary>
/// <param name="query">Запрос в свободной форме</param>
/// <returns></returns>
[HttpGet] [HttpGet]
public IAsyncEnumerable<Product> SearchProducts([FromQuery] string query) public IAsyncEnumerable<Product> SearchProducts([FromQuery] string query)
{ {

View File

@ -5,6 +5,8 @@ using RhSolutions.Api.Middleware;
using RhSolutions.QueryModifiers; using RhSolutions.QueryModifiers;
using RhSolutions.QueryModifiers.DrinkingWaterHeatingFittings; using RhSolutions.QueryModifiers.DrinkingWaterHeatingFittings;
using RhSolutions.QueryModifiers.DrinkingWaterHeatingPipes; using RhSolutions.QueryModifiers.DrinkingWaterHeatingPipes;
using Microsoft.OpenApi.Models;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -60,7 +62,25 @@ builder.Services.AddKeyedTransient<IProductQueryModifier, Sleeve>("Монтаж
.AddKeyedTransient<IProductQueryModifier, StabilPipe>("Stabil") .AddKeyedTransient<IProductQueryModifier, StabilPipe>("Stabil")
.AddKeyedTransient<IProductQueryModifier, BlackPipe>("Black"); .AddKeyedTransient<IProductQueryModifier, BlackPipe>("Black");
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "RhSolutions API",
Description = "API к базе данных артикулов РЕХАУ для поиска с помощью ML.NET и полнотестового поиска PostgreSQL",
Contact = new OpenApiContact
{
Name = "Serghei Cebotari",
Url = new Uri("https://cebotari.ru/"),
Email = @"serghei@cebotari.ru"
}
});
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
var app = builder.Build(); var app = builder.Build();

View File

@ -5,6 +5,8 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>1c307973-55cf-4d5c-a4f8-1def6b58ee3c</UserSecretsId> <UserSecretsId>1c307973-55cf-4d5c-a4f8-1def6b58ee3c</UserSecretsId>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>