Search code examples
c#asp.net-coregraphql.net-5hotchocolate

Hot Chocolate (GraphQL) interceptor/middleware to get IQueryable before data fetch


I need to do something extra with the IQueryable generated, but im not able to create an interceptor in order to get the IQueryable (e.g log the query created by the GraphQL request).

Im still diving into the great material that is Hot chocolate, but for starters i have this:

enter image description here

Straight forward right? But now want an interceptor(or something like that) that gives me the rest of the generated IQueryable before the result to the body response.

Thank you,


Solution

  • You can do this by using a middleware.

    public class Query
    {
        [UseYourCustom]
        [UseProjection]
        [UseFiltering]
        [UseSorting]
        public IQueryable<Person> GetPersons() => //...
    }
    
    public class UseYourCustomAttribute : ObjectFieldDescriptorAttribute
    {
        public override void OnConfigure(
            IDescriptorContext context,
            IObjectFieldDescriptor descriptor,
            MemberInfo member)
        {
            descriptor.Use(next => async context =>
            {
                // before the resolver pipeline
                await next(context);
                // after the resolver pipeline
    
                if (context.Result is IQueryable<Person> query)
                {
                   // all middleware are applied to `query`
                }
            });
        }
    }
    

    In Version 12 you will also be able to do the following:

    public class Query
    {
        [UseProjection]
        [UseFiltering]
        [UseSorting]
        public IQueryable<Person> GetPersons(IResolverContext context)
        {
            IQueryable<Person> person = //...
    
            var allMiddlewareApplied = persons
                .Sort(context)
                .Filter(context)
                .Project(context);
    
            return allMiddlewareApplied
        }
    }