飞雪团队

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 18071|回复: 0

使用Hot Chocolate和.NET 6构建GraphQL应用(8) —— 实现Mutate添加数据 ...

[复制链接]

9171

主题

9259

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
29843
发表于 2022-2-12 14:35:41 | 显示全部楼层 |阅读模式
: g  q! x4 C9 {& g0 K- O
<h2 id="系列导航">系列导航</h2>
( z  s+ }6 _, D% U/ Y# r- G<p><a  href="https://www.cnblogs.com/code4nothing/p/graphql-net6-0.html">使用Hot Chocolate和.NET 6构建GraphQL应用文章索引</a></p>3 n9 H9 @8 ^1 E) A# n: p
<h2 id="需求">需求</h2>
8 V8 S, X4 O* ~3 k<p>在讨论完GraphQL中的查询需求后,这篇文章我们将演示如何实现GraphQL中的数据添加任务。</p>& ]: ~- m( V" `3 T: H; t) W) d) G- I9 h
<h2 id="思路">思路</h2>
3 O8 d3 W) w1 k5 I7 [$ d# p<p>在GraphQL中,对数据进行查询使用<code>query</code>,而对于修改数据则需要使用<code>mutation</code>,包括新增和修改数据。Hot Chocolate在使用Mutation的逻辑上和使用Query的基本一致,但是需要根据需要定义用于创建或者更新的数据对象,所以我们直接进行实现。</p>
; W& J4 _* e  e; N& k/ D<h2 id="实现">实现</h2>
% S, d) X0 {$ A( h2 @! {<p>为了保持简单,我们先定义以下两个类型:</p>* h/ \) W% v$ \  _+ h$ _# r5 D" A
<pre><code class="language-c#">// 定义新增Post的参数8 c9 U- i( v* s/ E* g
public record AddPostInput(string Title, string Author);$ o2 Z) J# h: g$ u  b0 @, M
% V- @" f0 x& D
// 定义新增Post的返回对象
% }' d! Y. e% V2 k( H: spublic record AddPostPayload(Post Post);# U  H7 _+ U% t  R: h( K
</code></pre>
1 m$ |9 `2 g- s( Z6 k# i* K9 @3 c<p>新建<code>Mutation.cs</code>用来定义相关接口:</p>
8 Y5 B; r- x; n<ul>
) Z8 u7 @; t4 D) @<li><code>Mutation.cs</code></li>
6 l! j0 h2 Q3 E: V/ C" j/ I</ul>
* u  v3 P5 J/ j8 _<pre><code class="language-c#">namespace PostGraphi.Api.GraphQL;
% x3 s6 w; U/ c6 v$ ~' Z  y/ V; C; `" |; c* V
public class Mutation
6 M- F3 a1 B, {! B4 E) B$ r9 D{& ~0 Y* a+ x' U8 M& `. M1 N
    public async Task&lt;AddPostPayload&gt; AddPostAsync(AddPostInput input, [Service] IRepository&lt;Post&gt; repository)8 m3 l, D7 ~* t# {3 O" ?) k
    {" k$ M* {) X. {/ M- B2 O! {0 e8 Y
        return new AddPostPayload(await repository.AddAsync(new Post
6 |* A% N1 w: W        {
1 b$ J) b4 h1 \            Title = input.Title,! l; l' {" L& o- t! w+ L7 u
            Author = input.Author  A( t$ g* l7 }$ n. w
        }));8 S+ Q; g4 H1 H5 C  t0 T; M$ J% r
    }7 W$ U  h$ E8 ?# T& D+ f
}  h- I( h0 r6 Q8 Q. C4 a

* [7 @" d% i  f/ V</code></pre>/ b  B5 z6 B+ q9 E, J
<p>最后在注入服务的地方进行配置:</p>8 a( ^) k# G" I1 M
<ul>
* Y) F! ~6 u; @<li><code>ProgramExtensions.cs</code></li>
8 m' p' O' A% v  U) ~</ul>' P4 t) \) P& m6 [! K# B
<pre><code class="language-c#">builder.Services
+ `4 b8 y2 p0 d* }- ^    .AddGraphQLServer()
5 l; m$ B& o9 K2 a+ j    .SetPagingOptions(new PagingOptions% S! o6 G/ k: P4 k. P  g5 Y/ z
    {
. i. N- x  E& c% {. l        MaxPageSize = 50,, [2 c$ l8 B7 C. Z0 Z" }! Q- C
        IncludeTotalCount = true
) R! M  J! E# _+ A6 H7 v" B  @    })
" K4 h/ ~+ u  L    .AddFiltering()" [+ D1 J/ G4 v
    .AddProjections()8 B" I$ P3 A+ C: M8 a
    .AddSorting()
9 D: b4 z! F' p# I6 \    .AddQueryType&lt;Query&gt;()
2 i5 W6 Y" X. O5 ]5 i    .AddMutationType&lt;Mutation&gt;()* y9 D4 H: ]9 p& a7 a
    .AddMutationConventions(new MutationConventionOptions- i& a# H  S3 D6 t
    {
  o% U9 l% P1 ^        ApplyToAllMutations = true,
  F0 z3 C+ f8 U        InputArgumentName = "input",; G; n; v7 K0 t+ A, r
        InputTypeNamePattern = "{MutationName}Input",
' `) J: D5 x$ g  f. Z) H        PayloadTypeNamePattern = "{MutationName}Payload",& N9 n/ p4 ]- ]
        PayloadErrorTypeNamePattern = "{MutationName}Error",
+ r6 l5 v9 w& P8 T/ W/ y) M        PayloadErrorsFieldName = "errors"/ H/ E; k5 g8 t9 f" l4 C0 @
    })1 n6 l# v) C/ V7 _4 W( L
    .AddType&lt;PostType&gt;();
9 H" i# y( V7 q2 G0 [: _</code></pre>
8 K$ I( ^8 \- N<p>这样就实现了新增Post的需求,下面我们来验证一下。</p>: l# w+ h' O% I% x& M
<h2 id="验证">验证</h2>
" x3 j# B9 p& @( o) y0 t# {<p>启动<code>Api</code>项目,调用接口:</p>
4 r  V* Q- G4 `6 ?8 {: v<p><img src="https://img2022.cnblogs.com/blog/2487237/202202/2487237-20220211104544617-1400586374.png" ></p>
8 {( @3 r' G. g. ]<p>终端的日志输出如下:</p>9 N; d7 X. l- |/ z
<pre><code class="language-bash">[10:45:15 INF] Executed DbCommand (1ms) [Parameters=[@p0='?' (DbType = Guid), @p1='?', @p2='?' (Size = 13), @p3='?', @p4='?' (DbType = DateTime), @p5='?', @p6='?' (DbType = DateTime), @p7='?', @p8='?', @p9='?' (DbType = DateTime), @p10='?' (Size = 30)], CommandType='Text', CommandTimeout='30']' C$ [. i; c. A
INSERT INTO "Posts" ("Id", "Abstraction", "Author", "Content", "Created", "CreatedBy", "LastModified", "LastModifiedBy", "Link", "PublishedAt", "Title")% \( Z4 Y, e6 M. n
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10);  [: B( q, t  J7 t1 i
[10:45:15 INF] Executed endpoint 'Hot Chocolate GraphQL Pipeline'
( S4 D0 b, B: ^2 `/ |</code></pre>
& b' ]6 h( `4 i+ G9 L8 a8 X* X<p>可以看到新建的Post已经存储到数据库中了,我们可以通过查询接口来获取详情:</p>1 l5 Q: Y, P- B, u& l' p& f6 L
<p><img src="https://img2022.cnblogs.com/blog/2487237/202202/2487237-20220211104851825-1533915064.png" ></p>2 J1 @2 Q9 j5 P
<h2 id="总结">总结</h2>
  E# B& ~' k7 |. k4 w( W<p>在本文中我们实现了简单的新增Post操作,这里还有一些涉及到错误处理的内容,我没有在文章中演示,可以参考官方文档 <a  href="https://chillicream.com/docs/hotchocolate/defining-a-schema/mutations/#errors">Errors</a>,在自定义异常对象后,有三种方式可以进行错误处理:直接返回异常;使用异常工厂方法;使用构造函数。甚至可以在<code>AggregateExceptions</code>中一次性返回多个异常。基本思路都是通过添加属性<code>[Error(typeof(SomeUserDefinedException))]</code>来实现的。</p>- ]; z! p: f9 q/ e3 i- v5 f9 x- B
<p>在下一篇文章中,我们通过<code>Mutation</code>对已有数据进行更新。</p>6 @+ @) E/ z  g6 L+ }' t
3 ^" B0 E- O; V# E- P+ ]
回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|飞雪团队

GMT+8, 2026-9-2 23:57 , Processed in 0.192273 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表