summaryrefslogtreecommitdiff
path: root/RhSolutions.Api/Middleware/QueryModifier.cs
blob: f349e487ffba625bf8ad418dae725fec14ee96fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using Microsoft.AspNetCore.Http.Extensions;
using RhSolutions.Api.Services;
using RhSolutions.MLModifiers;

namespace RhSolutions.Api.Middleware;

public class QueryModifier
{
	private RequestDelegate _next;
	private IServiceProvider _provider;
	private IProductMLModifier? _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<IProductMLModifier>(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);
	}
}