.Net6 + GraphQL + MongoDb 实现Query分页功能
介绍
本节我们给Query加上分页.
正文
修改Program
builder.Services
.AddGraphQLServer()
.AddQueryType<PostQuery>()
.AddMongoDbFiltering()
.AddMongoDbSorting()
.AddMongoDbProjections()
.SetPagingOptions(new PagingOptions
{
MaxPageSize = 50,
IncludeTotalCount = true
});
修改PostQuery.cs
public class PostQuery
{
[UsePaging]
[UseOffsetPaging]
[UseProjection]
[UseFiltering]
[UseSorting]
public IExecutable<Post> GetPosts([Service] DbContext db)
{
return db.Post.AsExecutable();
}
}
这时候我们去https://localhost:7145/graphql/
调用的接口.加上order排序
query testGetPost {
posts(where: {
title: { eq: "1 - introduction to graphql" }
}
order: [{ title: ASC }) {
id
title
comments {
name
}
}
}
我们看下mongodb的监控信息,已经对我们的order做出了变化
{
"op": "query",
"ns": "GQL_Example.post",
"command": {
"find": "post",
"filter": {
"Title": {
"$eq": "1 - introduction to graphql"
}
},
"sort": {
"Title": NumberInt("1")
},
"projection": {
"Comments.Name": NumberInt("1"),
"Title": NumberInt("1"),
"_id": NumberInt("1")
},
"$db": "GQL_Example",
"lsid": {
"id": UUID("3b2fc182-6821-4216-96a3-d3db42350015")
},
"$clusterTime": {
"clusterTime": Timestamp(1676094001, 1),
"signature": {
"hash": BinData(0, "AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId": NumberLong("0")
}
}
}
}
结语
本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用
联系作者:加群:867095512 @MrChuJiu