Complete example of adding custom Operation #3138
-
Hello! I am trying to follow how to add a custom operation as described on Extending Filtering. Unfortunately, there seems to be some missing/outdated pieces to completely add the I'll probably revisit this next week and will likely look into HC source code to figure out how the built-in operations are added. But I'm hoping someone can share a complete working sample of adding a custom operation before I get to revisit it again. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I think I got it.. What's missing was public static class CustomOperations
{
public const int Like = 1025;
}
public class CustomFilteringConvention : FilterConvention
{
protected override void Configure(IFilterConventionDescriptor descriptor)
{
descriptor.AddDefaults();
descriptor
.Operation(CustomOperations.Like)
.Name("like");
descriptor
.Configure<StringOperationFilterInputType>(_ => _
.Operation(CustomOperations.Like)
.Type<StringType>()
.Extend()
.OnBeforeCreate(_ => _.Handler = new QueryableStringInvariantEqualsHandler()));
}
}
// from https://chillicream.com/docs/hotchocolate/api-reference/extending-filtering/#extending-iqueryable
// but only applied to `like` custom operation as shown above
public class QueryableStringInvariantEqualsHandler : QueryableStringOperationHandler
{
private static readonly MethodInfo _toLower = typeof(string)
.GetMethods()
.Single(
_ => _.Name == nameof(string.ToLower) &&
_.GetParameters().Length == 0);
protected override int Operation => CustomOperations.Like;
public override Expression HandleOperation(
QueryableFilterContext context,
IFilterOperationField field,
IValueNode value,
object parsedValue)
{
var property = context.GetInstance();
var str = (string)parsedValue;
return Expression.Equal(
Expression.Call(property, _toLower),
Expression.Constant(str.ToLower()));
}
}
// in Startup.ConfigureServices
services
.AddGraphQLServer()
.AddConvention<IFilterConvention, CustomFilterConvention>()
.AddFiltering() |
Beta Was this translation helpful? Give feedback.
I think I got it.. What's missing was
Type<StringType>().Extend().OnBeforeCreate(_ => _.Handler = ...)
to fully configure the custom operation.