.Net6 + GraphQL + MongoDb 实现一个简单的Query
介绍
上一节我们简单搭建了项目的结构
本节我们来实现一个简单Query查询
正文
新建PostQuery.cs
, 新建Core文件夹存放
public class PostQuery
{
public IExecutable<Post> GetPosts([Service] DbContext db)
{
## 种子数据来点
## await _db.Post.InsertOneAsync(new Post()
## {
## Title = "1 - introduction to graphql",
## Abstraction = "this is an introduction post for graphql",
## Content = "some random content for post 1",
## Author = "code4nothing",
## PublishedAt = DateTime.Now.AddDays(-2),
## Link = "http://link-to-post-1.html",
## Comments = new List<Comment>
## {
## new() { CreatedAt = DateTime.Now.AddHours(-3), Content = "comment 01 for post 1", Name = "kindUser01" },
## new() { CreatedAt = DateTime.Now.AddHours(-2), Content = "comment 02 for post 1", Name = "kindUser01" },
## new() { CreatedAt = DateTime.Now, Content = "comment 03 for post 1", Name = "kindUser02" }
## },
## });
return db.Post.AsExecutable();
}
}
修改Program
builder.Services
.AddGraphQLServer()
.AddQueryType<PostQuery>()
启动项目,打开下面链接
https://localhost:7145/graphql/
https://localhost:7145/graphql-voyager
可以输入下面命令调用查询接口
query testGetPost {
posts {
id
title
comments {
name
}
}
}
这是MongoDb的监控信息,从监控信息上面来看我们调用数据使用的是全表检索。下一节我们将按需查询
{
"op": "query",
"ns": "GQL_Example.post",
"command": {
"find": "post",
"filter": { },
"$db": "GQL_Example",
"lsid": {
"id": UUID("ac10bc25-cf94-4859-8d46-ade1d66e670b")
}
},
}
结语
本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用
联系作者:加群:867095512 @MrChuJiu