Skip to content

Reshaping data effortlessly with a C# data shaping library.

License

Notifications You must be signed in to change notification settings

HamedStack/HamedStack.DataShaping

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DataShaper Utility for ASP.NET Core

The DataShaper<T> service allows you to shape objects and collections dynamically by selecting specific fields at runtime. This is useful for implementing dynamic field selection in REST APIs (e.g., for performance or customization).


🔧 Features

  • Dynamically select properties of an object or collection.
  • Useful for building clean, efficient API responses.
  • Integrates easily with ASP.NET Core's Dependency Injection (DI) system.

📦 Installation

Just add the IDataShaper<T> and DataShaper<T> classes to your project. Then register the service in the DI container.


🧩 Registering with Dependency Injection

Add this to your Startup.cs (ASP.NET Core 5) or Program.cs (ASP.NET Core 6+):

builder.Services.AddScoped(typeof(IDataShaper<>), typeof(DataShaper<>));

This allows the service to be injected anywhere using generics.


✅ Example Usage

Model

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; } = default!;
    public string LastName { get; set; } = default!;
    public int Age { get; set; }
}

Controller or Service

public class PeopleService
{
    private readonly IDataShaper<Person> _dataShaper;

    public PeopleService(IDataShaper<Person> dataShaper)
    {
        _dataShaper = dataShaper;
    }

    public IEnumerable<Dictionary<string, object?>> GetPeopleShaped(IEnumerable<Person> people, string? fields)
    {
        return _dataShaper.ShapeData(people, fields);
    }
}

Sample Usage

var people = new List<Person>
{
    new Person { Id = 1, FirstName = "Alice", LastName = "Smith", Age = 30 },
    new Person { Id = 2, FirstName = "Bob", LastName = "Johnson", Age = 25 }
};

var shaped = _dataShaper.ShapeData(people, "Id,FirstName");

Output:

[
  { "Id": 1, "FirstName": "Alice" },
  { "Id": 2, "FirstName": "Bob" }
]

If fields is null or empty, all properties will be included.


📝 Notes

  • Property names in the fields string are case-insensitive.
  • If a field in the string doesn’t exist on the model, it will be ignored.
  • Works best when combined with API query parameters like ?fields=Id,Name.