Mb...R
Mb...R

Reputation: 78

Need better design at forming c# object for an API rquest

I have json request that I need to send to an API which is of following format

{
    "FilterName": "City",
    "Operator": "is", 
    "Values": ["city name"]
},

I the above request the filtername can be City, state, street and for each there are a certain set of operators allowed for city : [is,contains], state:[is], streetNumber"[range,is,contains]

I want to create c# pattern for this where in I can

Create a class which force the use to the list of filters we provide and appropriate operators alond with it.

API provides 100 filter types but I need my application to allow only few of them .

forexample:

A request with state and city ( below request just my thought of how it should look like, it doenst have to be fluent )

Filterarray().AddFilter(StreetName().AddOperator("is)) // addoperator should allow is Filterarray().AddFilter(Cities().AddOperator("is/contans)) // addoperator should allow is / contains

Currently Im sending hardcoded values lie new Filter("state","is","value"). I dont want to do this, I need to learn something more refine. Please let me know your suggestions for a better way to add each filter and maintainable pattern

Upvotes: 0

Views: 77

Answers (1)

Michael
Michael

Reputation: 1276

I think a factory pattern with multiple factory methods (the allowed operations) is fine for this use case:

    public abstract class Filter
    {
        public string FilterName { get; }
        public string Operator { get; }
        public string[] Values { get; }

        protected Filter(string filterName, string op, string[] values)
        {
            FilterName = filterName;
            Operator = op;
            Values = values;
        }
    }

    public class CityFilter : Filter
    {
        private CityFilter(string op, string value) : base("City", op, new string[] { value })
        { }

        public static CityFilter Is(string value) => new CityFilter("is", value);

        public static CityFilter Contains(string value) => new CityFilter("contains", value);
    }

    public class StateFilter : Filter
    {
        private StateFilter(string op, string value) : base("State", op, new string[] { value })
        { }

        public static StateFilter Is(string value) => new StateFilter("is", value);
    }

    public class Program
    {
        public static async Task Main(string[] args)
        {
            var city = CityFilter.Contains("city name");
            var state = StateFilter.Is("state name");
            // Serialize and send filter
        }
    }

Upvotes: 1

Related Questions