系列导航

使用Hot Chocolate和.NET 6构建GraphQL应用文章索引

需求

对于查询来说,还有一大需求是针对查询的数据进行过滤,本篇文章我们准备实现GraphQL中基本的查询过滤。

思路

Hot Chocolate提供了UseFiltering属性来用于构造包含查询过滤的SQL语句,所以我们直接使用就好了。

实现

要使用Filtering属性,需要先在添加服务依赖注入的时候指定:

  • ProgramExtension.cs
builder.Services
    .AddGraphQLServer()
    .AddFiltering()
    .AddProjections()
    .AddQueryType<Query>()
    .AddType<PostType>();

然后在接口上方添加UseProjection即可,注意属性添加的顺序。

  • Query.cs
[UseProjection]
[UseFiltering]
public IQueryable<Post> GetPosts([Service] IRepository<Post> repository) => repository.GetAsQueryable();

这样就实现了查询的过滤,非常简单,下面我们来验证一下。

验证

启动Api项目,调用接口:

可以看到在返回体中,只包含Title内含有graphql的结果了,我们再来看一下控制台输出的EF Core日志:

[22:43:08 INF] Executing endpoint 'Hot Chocolate GraphQL Pipeline'
[22:43:08 INF] Executed DbCommand (0ms) [Parameters=[@__p_0='?' (Size = 7)], CommandType='Text', CommandTimeout='30']
SELECT "p"."Id", "p"."Title", "p"."Author", "c"."Content", "c"."Id", "t0"."Name", "t0"."PostsId", "t0"."TagsId", "t0"."Id"
FROM "Posts" AS "p"
LEFT JOIN "Comments" AS "c" ON "p"."Id" = "c"."PostId"
LEFT JOIN (
    SELECT "t"."Name", "p0"."PostsId", "p0"."TagsId", "t"."Id"
    FROM "PostTag" AS "p0"
    INNER JOIN "Tags" AS "t" ON "p0"."TagsId" = "t"."Id"
) AS "t0" ON "p"."Id" = "t0"."PostsId"
WHERE (@__p_0 = '') OR (instr("p"."Title", @__p_0) > 0)
ORDER BY "p"."Id", "c"."Id", "t0"."PostsId", "t0"."TagsId"
[22:43:08 INF] Executed endpoint 'Hot Chocolate GraphQL Pipeline'

从日志中可以看到Hot Chocolate已经为生成的SQL语句添加了Where查询子句了,在示例中我们选择了contains作为过滤的条件来展示,实际上可以进行过滤的条件有很多:

总结

在本文中我们实现了查询过滤,下一篇文章将会介绍如何进行查询数据的排序。