I've been trying and failing to create a custom filter for Date
types using Hot Chocolate. The issue is that the HC defaults to DateTimeOffset
, but for filtering dates coming from the application, the time portion doesn't make any sense. I've tried to create a custom filter type, but I'm running into the issue that in the model that is being filtered, the date fields are all nullable. So the following code throws an exception.
public class QueryableDateLessThanEqualToHandler : QueryableComparableLowerThanOrEqualsHandler
{
public QueryableDateTimeLessThanOrEqualToFilter(ITypeConverter typeConverter, InputParser inputParser) : base(typeConverter,inputParser)
{
}
private static readonly MethodInfo _toShortDateString = typeOf(DateTime)
.GetMethods()
.Single(x => x.Name == nameof(DateTime.ToShortDateString);
protected override int Operation => DefaultFilterOperations.LowerThanOrEquals;
public override Expression HandleOperation(
QueryableFIlterContext context,
IFilterOperationField field,
IValueNode value,
object? parsedValue)
{
try
{
Expression property = context.GetInstance();
if(parsedValue is DateTimeOffset inputDateTimeOffset)
{
DateTime filterDate = inputDateTimeOffset.DateTime;
return Expression.LessThanOrEqual(
Expression.Call(property, _toShortDateString),
Expression.Constant(filterDate.ToShortDateString()));
}
else if(parsedValue is DateTime inputDateTime) //I have both datetimeoffset and datetime in the model I'm filtering
{
return Expression.LessThanOrEqual(
Expression.Call(property, _toShortDateString),
Expression.Constant(inputDateTime.ToShortDateString()));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.message);
return Expression.LessThanOrEqual(
Expression.Constant(0),Expression.Constant(1));
}
}
}
The exception I'm getting is Method 'System.String ToShortDateString()' declared on type 'System.DateTime' cannot be called with stance of type 'System.Nullable'1[System.DateTimeOffset]'
I believe I understand why I'm getting this error, because the acutal field that is being filtered is a nullable DatetimeOffset, but I have no idea how to convert it to a not nullable field in this context.
I have a feeling it is somewhere in the _toShortDateString
, but how to do that has so far alluded me.
This feels like it should be straight forward, but at this point I'm totally lost.
Any help would be appreciated.