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

40 lines
1.1 KiB
C#

using Microsoft.AspNetCore.Http.Extensions;
using RhSolutions.Api.Services;
using RhSolutions.QueryModifiers;
namespace RhSolutions.Api.Middleware;
public class QueryModifier
{
private RequestDelegate _next;
private IServiceProvider _provider;
private IProductQueryModifier? _modifier;
public QueryModifier(RequestDelegate nextDelegate, IServiceProvider provider)
{
_next = nextDelegate;
_provider = provider;
}
public async Task Invoke(HttpContext context, IProductTypePredicter typePredicter)
{
if (context.Request.Method == HttpMethods.Get
&& context.Request.Path == "/api/search")
{
string query = context.Request.Query["query"].ToString();
var productType = typePredicter.GetPredictedProductType(query);
_modifier = _provider.GetRequiredKeyedService<IProductQueryModifier>(productType);
if (_modifier == null) return;
if (_modifier.TryQueryModify(query, out var modified))
{
QueryBuilder qb = new()
{
{"query", modified}
};
context.Request.QueryString = qb.ToQueryString();
}
}
await _next(context);
}
}