.Net6 + GraphQL + MongoDb 实现Mutate添加数据

介绍

Query的部分我们讲完了,现在讲一下Mutate(就是操作增修删) 本节讲一下新增

正文

新建Requests文件夹

    public record AddPostInput(string Title, string Author);    


    public record AddPostPayload(Post Post);

新建PostMutation.cs

    public class PostMutation
    {
        public async Task<AddPostPayload> CreatePostAsync(
            [Service] DbContext db,
            AddPostInput input)
        {
            var entity = new Post()
            {
                Title = input.Title,
                Abstraction = "this is an introduction post for graphql",
                Content = "some random content for post 1",
                Author = input.Author,
                PublishedAt = DateTime.Now.AddDays(-2),
                Link = "http://link-to-post-1.html",
                Comments = new List<Comment>
                {
                    new() { CreatedAt = DateTime.Now, Content = "test  comment 03 for post 1", Name = "kindUser02" }
                },
            };

            await db.Post.InsertOneAsync(entity);

            return new AddPostPayload(entity);
        }
    }

修改Program

builder.Services
    .AddGraphQLServer()
    .AddQueryType<PostQuery>()
    .AddMutationType<PostMutation>()
    .AddMongoDbFiltering()
    .AddMongoDbSorting()
    .AddMongoDbProjections()
    .AddMongoDbPagingProviders()
    .SetPagingOptions(new PagingOptions
    {
        MaxPageSize = 50,
        IncludeTotalCount = true
    });

这时候我们去https://localhost:7145/graphql/调用接口

mutation {
  createPost(input: { title: "test ttt", author: "aaaaaaaa" }) {
    post {
      title
    }
  }
}

query testGetPost {
  posts(where: {
      title: { eq: "1 - introduction to graphql" }
    }) {
    id
    title
    comments {
      name
    }
  }
}

结语

本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用

联系作者:加群:867095512 @MrChuJiu

posted @ 2023-02-13 20:44  初久的私房菜  阅读(12028)  评论(0编辑  收藏  举报
作者:初久的私房菜
好好学习,天天向上
返回顶部小火箭
好友榜:
如果愿意,把你的博客地址放这里
张弛:https://blog.zhangchi.fun/