use. NET 6 to develop TodoList application (17) -- realizing data shaping

Series navigation and source code

demand

In the query scenario, another requirement is not very common, that is, to specify the returned fields in the front-end request, so let's demonstrate Data Shaping on the last topic of search.

target

Implement data shaping search requests.

Principles and ideas

For data shaping, we need to define some interfaces and generic class implementations to complete general functions, and then modify the corresponding query requests to realize specific functions.

realization

Define common interfaces and generic class implementations

  • IDataShaper.cs
using System.Dynamic;

namespace TodoList.Application.Common.Interfaces;

public interface IDataShaper<T>
{
    IEnumerable<ExpandoObject> ShapeData(IEnumerable<T> entities, string fieldString);
    ExpandoObject ShapeData(T entity, string fieldString);
}

And realize common functions:

  • DataShaper.cs
using System.Dynamic;
using System.Reflection;
using TodoList.Application.Common.Interfaces;

namespace TodoList.Application.Common;

public class DataShaper<T> : IDataShaper<T> where T : class
{
    public PropertyInfo[] Properties { get; set; }

    public DataShaper()
    {
        Properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    }

    public IEnumerable<ExpandoObject> ShapeData(IEnumerable<T> entities, string? fieldString)
    {
        var requiredProperties = GetRequiredProperties(fieldString);

        return GetData(entities, requiredProperties);
    }

    public ExpandoObject ShapeData(T entity, string? fieldString)
    {
        var requiredProperties = GetRequiredProperties(fieldString);

        return GetDataForEntity(entity, requiredProperties);
    }

    private IEnumerable<PropertyInfo> GetRequiredProperties(string? fieldString)
    {
        var requiredProperties = new List<PropertyInfo>();

        if (!string.IsNullOrEmpty(fieldString))
        {
            var fields = fieldString.Split(',', StringSplitOptions.RemoveEmptyEntries);
            foreach (var field in fields)
            {
                var property = Properties.FirstOrDefault(pi => pi.Name.Equals(field.Trim(), StringComparison.InvariantCultureIgnoreCase));
                if (property == null)
                {
                    continue;
                }

                requiredProperties.Add(property);
            }
        }
        else
        {
            requiredProperties = Properties.ToList();
        }

        return requiredProperties;
    }

    private IEnumerable<ExpandoObject> GetData(IEnumerable<T> entities, IEnumerable<PropertyInfo> requiredProperties)
    {
        return entities.Select(entity => GetDataForEntity(entity, requiredProperties)).ToList();
    }

    private ExpandoObject GetDataForEntity(T entity, IEnumerable<PropertyInfo> requiredProperties)
    {
        var shapedObject = new ExpandoObject();
        foreach (var property in requiredProperties)
        {
            var objectPropertyValue = property.GetValue(entity);
            shapedObject.TryAdd(property.Name, objectPropertyValue);
        }

        return shapedObject;
    }
}

Define extension method

To enable our Handle method call chain to be directly applied, we add a new DataShaperExtensions in Application/Extensions:

  • DataShaperExtensions.cs
using System.Dynamic;
using TodoList.Application.Common.Interfaces;

namespace TodoList.Application.Common.Extensions;

public static class DataShaperExtensions
{
    public static IEnumerable<ExpandoObject> ShapeData<T>(this IEnumerable<T> entities, IDataShaper<T> shaper, string? fieldString)
    {
        return shaper.ShapeData(entities, fieldString);
    }
}

Then add a method to the MappingExtensions static class we wrote earlier:

  • MappingExtensions.cs
// Omit other
public static PaginatedList<TDestination> PaginatedListFromEnumerable<TDestination>(this IEnumerable<TDestination> entities, int pageNumber, int pageSize)
{
    return PaginatedList<TDestination>.Create(entities, pageNumber, pageSize);   
}

Add dependency injection

In the dependencyinjection Add dependency injection to CS:

  • DependencyInjection.cs
// Omit others
services.AddScoped(typeof(IDataShaper<>), typeof(DataShaper<>));

Modify query request and Controller interface

On the basis of sorting in the previous article, we added a field to indicate the data shaping field and modify the Handle method accordingly:

  • GetTodoItemsWithConditionQuery.cs
using System.Dynamic;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using MediatR;
using TodoList.Application.Common.Extensions;
using TodoList.Application.Common.Interfaces;
using TodoList.Application.Common.Mappings;
using TodoList.Application.Common.Models;
using TodoList.Application.TodoItems.Specs;
using TodoList.Domain.Entities;
using TodoList.Domain.Enums;

namespace TodoList.Application.TodoItems.Queries.GetTodoItems;

public class GetTodoItemsWithConditionQuery : IRequest<PaginatedList<ExpandoObject>>
{
    public Guid ListId { get; set; }
    public bool? Done { get; set; }
    public string? Title { get; set; }
    // The front end indicates the fields to be returned
    public string? Fields { get; set; }
    public PriorityLevel? PriorityLevel { get; set; }
    public string? SortOrder { get; set; } = "title_asc";
    public int PageNumber { get; set; } = 1;
    public int PageSize { get; set; } = 10;
}

public class GetTodoItemsWithConditionQueryHandler : IRequestHandler<GetTodoItemsWithConditionQuery, PaginatedList<ExpandoObject>>
{
    private readonly IRepository<TodoItem> _repository;
    private readonly IMapper _mapper;
    private readonly IDataShaper<TodoItemDto> _shaper;

    public GetTodoItemsWithConditionQueryHandler(IRepository<TodoItem> repository, IMapper mapper, IDataShaper<TodoItemDto> shaper)
    {
        _repository = repository;
        _mapper = mapper;
        _shaper = shaper;
    }

    public Task<PaginatedList<ExpandoObject>> Handle(GetTodoItemsWithConditionQuery request, CancellationToken cancellationToken)
    {
        var spec = new TodoItemSpec(request);
        return Task.FromResult(
            _repository
                .GetAsQueryable(spec)
                .ProjectTo<TodoItemDto>(_mapper.ConfigurationProvider)
                .AsEnumerable()
                // Data shaping and paging return
                .ShapeData(_shaper, request.Fields)
                .PaginatedListFromEnumerable(request.PageNumber, request.PageSize)
            );
    }
}

Modify the Controller accordingly:

  • TodoItemController.cs
[HttpGet]
public async Task<ApiResponse<PaginatedList<ExpandoObject>>> GetTodoItemsWithCondition([FromQuery] GetTodoItemsWithConditionQuery query)
{
    return ApiResponse<PaginatedList<ExpandoObject>>.Success(await _mediator.Send(query));
}

verification

Start the Api item and execute the request to query TodoItem:

  • request

  • response

Let's add the filtering and search mentioned earlier to the request:

  • request

  • response

summary

For the request of data shaping, the key step is to use reflection to obtain all configured returnable properties of the object to be returned, and then filter and reorganize the values through the property name passed in from the front end. The implementation is relatively simple. But in the actual use process, I don't recommend it, except for some very applicable special scenarios. Individuals prefer to provide clear interface definition to the front end.

Keywords: webapi

Added by pozer69 on Wed, 05 Jan 2022 02:04:05 +0200