微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Hot Chocolate (GraphQL) 拦截器/中间件在获取数据之前获取 IQueryable

如何解决Hot Chocolate (GraphQL) 拦截器/中间件在获取数据之前获取 IQueryable

我需要对生成的 IQueryable 做一些额外的事情,但我无法创建拦截器来获取 IQueryable(例如记录由 GraphQL 请求创建的查询)。

我仍在深入研究热巧克力这一伟大的材料,但对于初学者来说,我有这个:

enter image description here

直接对吧?但现在想要一个拦截器(或类似的东西),在结果到正文响应之前给我生成的 IQueryable 的其余部分。

谢谢,

解决方法

您可以使用中间件来做到这一点。

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`
            }
        });
    }
}

在第 12 版中,您还可以执行以下操作:

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
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。