Uniconta FilterBuilder

Date: 2021-11-24
using System.Collections.Generic;
using System.Linq;
using Uniconta.Common;

namespace UnicontaAdapter.Helpers
{
    public class FilterBuilder
    {
        private readonly List<PropValuePair> result = new();

        private object ConvertValue(object src)
        {
            if (src is bool b)
            {
                return b ? "1" : "0";
            }
            return src;
        }

        private FilterBuilder AddWhere(string field, object value, CompareOperator op)
        {
            result.Add(PropValuePair.GenereteWhereElements(field, ConvertValue(value), op));
            return this;
        }

        public FilterBuilder WhereEqual(string field, object value) => AddWhere(field, value, CompareOperator.Equal);
        public FilterBuilder WhereNotEqual(string field, object value) => AddWhere(field, value, CompareOperator.NotEqual); 
        public FilterBuilder WhereStartsWith(string field, object value) => AddWhere(field, value, CompareOperator.StartsWith);
        public FilterBuilder WhereContains(string field, object value) => AddWhere(field, value, CompareOperator.Contains);
        public FilterBuilder WhereGreaterThan(string field, object value) => AddWhere(field, value, CompareOperator.GreaterThan);
        public FilterBuilder WhereGreaterThanOrEqual(string field, object value) => AddWhere(field, value, CompareOperator.GreaterThanOrEqual);
        public FilterBuilder WhereLessThan(string field, object value) => AddWhere(field, value, CompareOperator.LessThan);

        public FilterBuilder Skip(int number)
        {
            result.Add(PropValuePair.GenereteSkipN(number));
            return this;
        }

        public FilterBuilder Take(int number)
        {
            result.Add(PropValuePair.GenereteTakeN(number));
            return this;
        }

        public FilterBuilder OrderBy(string field)
        {
            result.Add(PropValuePair.GenereteOrderByElement(field, false));
            return this;
        }

        public FilterBuilder OrderByDescending(string field)
        {
            result.Add(PropValuePair.GenereteOrderByElement(field, true));
            return this;
        }

        public IEnumerable<PropValuePair> Build() => result.ToList();
    }
}

57300cookie-checkUniconta FilterBuilder