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

40 lines
1.1 KiB
C#
Raw Permalink Normal View History

2023-10-20 22:35:44 +03:00
using Microsoft.AspNetCore.Http.Extensions;
using RhSolutions.Api.Services;
2023-10-10 22:26:16 +03:00
using RhSolutions.QueryModifiers;
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;
private IProductQueryModifier? _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);
2023-12-30 14:43:25 +03:00
_modifier = _provider.GetRequiredKeyedService<IProductQueryModifier>(productType);
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
}