| | | 1 | | using Microsoft.AspNetCore.Mvc.ModelBinding; |
| | | 2 | | using Microsoft.Extensions.DependencyInjection; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using Plainquire.Filter.Abstractions; |
| | | 5 | | using System; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | using System.Linq; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | |
| | | 10 | | namespace Plainquire.Filter.Mvc.ModelBinders; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// ModelBinder for <see cref="EntityFilter{TEntity}"/> |
| | | 14 | | /// Implements <see cref="IModelBinder" /> |
| | | 15 | | /// </summary> |
| | | 16 | | /// <seealso cref="IModelBinder" /> |
| | | 17 | | public class EntityFilterModelBinder : IModelBinder |
| | | 18 | | { |
| | | 19 | | /// <inheritdoc /> |
| | | 20 | | public Task BindModelAsync(ModelBindingContext bindingContext) |
| | | 21 | | { |
| | 12 | 22 | | if (bindingContext == null) |
| | 0 | 23 | | throw new ArgumentNullException(nameof(bindingContext)); |
| | | 24 | | |
| | 12 | 25 | | var request = bindingContext.ActionContext.HttpContext.Request; |
| | | 26 | | |
| | 12 | 27 | | var filteredType = bindingContext.ModelType.GetGenericArguments()[0]; |
| | 12 | 28 | | var serviceProvider = bindingContext.ActionContext.HttpContext.RequestServices; |
| | 12 | 29 | | var configuration = GetFilterConfiguration(filteredType, serviceProvider); |
| | 12 | 30 | | var entityFilter = EntityFilterFactory.Create(filteredType, configuration); |
| | | 31 | | |
| | 12 | 32 | | var filters = request.Query |
| | 12 | 33 | | .SelectMany(kvp => kvp.Value.Select(value => new KeyValuePair<string, string?>(kvp.Key, value))) |
| | 12 | 34 | | .ToArray(); |
| | | 35 | | |
| | 12 | 36 | | entityFilter.ApplyFromSyntax(filteredType, filters); |
| | | 37 | | |
| | 12 | 38 | | bindingContext.Result = ModelBindingResult.Success(entityFilter); |
| | | 39 | | |
| | 12 | 40 | | return Task.CompletedTask; |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | private static FilterConfiguration? GetFilterConfiguration(Type? entityType, IServiceProvider serviceProvider) |
| | | 44 | | { |
| | 12 | 45 | | if (entityType == null) |
| | 0 | 46 | | return null; |
| | | 47 | | |
| | 12 | 48 | | var entityFilterType = typeof(EntityFilter<>).MakeGenericType(entityType); |
| | 12 | 49 | | var prototypeConfiguration = ((EntityFilter?)serviceProvider.GetService(entityFilterType))?.Configuration; |
| | 12 | 50 | | var injectedConfiguration = serviceProvider.GetService<IOptions<FilterConfiguration>>()?.Value; |
| | | 51 | | |
| | 12 | 52 | | var configuration = prototypeConfiguration ?? injectedConfiguration; |
| | 12 | 53 | | return configuration; |
| | | 54 | | } |
| | | 55 | | } |