0
0
RhSolutions-Api/RhSolutions.Api/Middleware/QueryModifier.cs

40 lines
1.0 KiB
C#
Raw Normal View History

2023-10-20 22:35:44 +03:00
using Microsoft.AspNetCore.Http.Extensions;
using RhSolutions.Api.Services;
2024-01-26 15:50:41 +03:00
using RhSolutions.MLModifiers;
2023-09-19 14:56:55 +03:00
namespace RhSolutions.Api.Middleware;
public class QueryModifier
{
2023-10-20 22:35:44 +03:00
private RequestDelegate _next;
2023-12-30 14:43:25 +03:00
private IServiceProvider _provider;
2024-01-26 15:50:41 +03:00
private IProductMLModifier? _modifier;
2023-09-19 14:56:55 +03:00
2023-12-30 14:43:25 +03:00
public QueryModifier(RequestDelegate nextDelegate, IServiceProvider provider)
2023-10-20 22:35:44 +03:00
{
_next = nextDelegate;
2023-12-30 14:43:25 +03:00
_provider = provider;
2023-10-20 22:35:44 +03:00
}
2023-09-19 14:56:55 +03:00
2023-12-30 14:43:25 +03:00
public async Task Invoke(HttpContext context, IProductTypePredicter typePredicter)
2023-10-20 22:35:44 +03:00
{
if (context.Request.Method == HttpMethods.Get
&& context.Request.Path == "/api/search")
{
string query = context.Request.Query["query"].ToString();
var productType = typePredicter.GetPredictedProductType(query);
2024-01-26 15:50:41 +03:00
_modifier = _provider.GetRequiredKeyedService<IProductMLModifier>(productType);
2023-12-30 14:43:25 +03:00
if (_modifier == null) return;
if (_modifier.TryQueryModify(query, out var modified))
2023-10-20 22:35:44 +03:00
{
QueryBuilder qb = new()
{
{"query", modified}
};
context.Request.QueryString = qb.ToQueryString();
}
}
await _next(context);
}
2023-09-19 14:56:55 +03:00
}