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

40 lines
1.0 KiB
C#

using Microsoft.AspNetCore.Http.Extensions;
using RhSolutions.Api.Services;
using RhSolutions.Parsers;
namespace RhSolutions.Api.Middleware;
public class QueryModifier
{
private RequestDelegate _next;
private IServiceProvider _provider;
private IProductParser? _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 input = context.Request.Query["query"].ToString();
var productType = typePredicter.GetPredictedProductType(input);
_modifier = _provider.GetRequiredKeyedService<IProductParser>(productType);
if (_modifier == null) return;
if (_modifier.TryParse(input, out var output))
{
QueryBuilder qb = new()
{
{"query", output}
};
context.Request.QueryString = qb.ToQueryString();
}
}
await _next(context);
}
}