I am building an application that will interact with an API. My service layer will call the repository which will request data from the API. I want to be able to pass filters to the repository and came up with the following. I am just curious if there are better ways of doing this?
First, I created an interface called IFilter
:
public interface IFilter
{
string GetFilterName();
string GetFilterValue();
}
I then have a bunch of filters, for example:
public class CreatedAfterFilter : IFilter
{
readonly string _name = "CreatedAfter";
DateTime _value;
public CreatedAfterFilter(DateTime value)
{
this._value = value;
}
public string GetFilterValue()
{
return _value.ToString("yyyy-MM-ddTHH:mm:ss+00:00");
}
public string GetFilterName()
{
return _name; ;
}
}
...or
public class OrdersFilter : IFilter
{
readonly string _name = "OrderIdList";
List<Order> _value;
public OrdersFilter(List<Order> value)
{
this._value = value;
}
public string GetFilterValue()
{
return '[' + String.Join(",", _value.Select(x => x.OrderId)) + ']';
}
public string GetFilterName()
{
return _name; ;
}
}
When I call my repository, I do something like this:
var filters = new List<IFilter>();
filters.Add(new CreatedAfterFilter(DateTime.UtcNow.AddDays(-110)));
filters.Add(new OrderFilter(1709359));
var orders = orderRepository.GetSingleOrder(filters);
Then in my code that calls the API, I do this to create the query string:
foreach (var filter in filters)
{
getParams.Add(new KeyValuePair<string, string>(filter.GetFilterName(), filter.GetFilterValue()));
}
Am I on the right track here? This is my first real time in writing C# an using Interfaces.