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

40 lines
1.0 KiB
C#
Raw Permalink Normal View History

2023-10-20 22:35:44 +03:00
using Microsoft.AspNetCore.Http.Extensions;
using RhSolutions.Api.Services;
2024-02-08 17:11:11 +03:00
using RhSolutions.Parsers;
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-02-08 17:11:11 +03:00
private IProductParser? _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")
{
2024-02-08 17:11:11 +03:00
string input = context.Request.Query["query"].ToString();
var productType = typePredicter.GetPredictedProductType(input);
_modifier = _provider.GetRequiredKeyedService<IProductParser>(productType);
2023-12-30 14:43:25 +03:00
if (_modifier == null) return;
2024-02-08 17:11:11 +03:00
if (_modifier.TryParse(input, out var output))
2023-10-20 22:35:44 +03:00
{
QueryBuilder qb = new()
{
2024-02-08 17:11:11 +03:00
{"query", output}
2023-10-20 22:35:44 +03:00
};
context.Request.QueryString = qb.ToQueryString();
}
}
await _next(context);
}
2023-09-19 14:56:55 +03:00
}