🧑🔬 测试我们的突变
现在我们有了我们的方案,
让我们通过打开新的终端窗口来启动服务器。在这里,我们将导航到


点击旁边的加号按钮(⊕)旁边的 incrementTrackViews
将其添加到我们的 操作面板中。这将预先填写一些信息!语法应该很熟悉,因为这与我们迄今为止查询的语法相同,尤其是在 升空 III 中,我们使用了 参数 和 变量。
mutation IncrementTrackViews($incrementTrackViewsId: ID!) {incrementTrackViews(id: $incrementTrackViewsId) {}}
✍️ 构建GraphQL突变
我们从 mutation
关键字开始,然后是 操作(IncrementTrackViews
是探索者为我们命名的)。在括号内,我们有一个由 $
符号表示的 变量,名为 incrementTrackViewsId
,它是一种 ID
类型,且是必需的。
此 变量设置在下面的 变量 部分。目前它设置为 null
,所以让我们将其更改为我们一直在使用的相同的轨道ID: c_0
。

{"incrementTrackViewsId": "c_0"}
回到 突变的 操作面板中!
在大括号内,我们列出了我们的突变入口点:incrementTrackViews
。它接收一个id
参数,我们将它设置为变量 incrementTrackViewsId
,与刚才设置为c_0
的相同。
现在在大括号的第二层内,我们可以开始添加我们的响应对象中可用的字段。这些字段在侧边栏中,这使得通过点击字段旁边的⊕(加号)按钮来构建这个突变变得非常容易。
我们希望看到code
,success
布尔值,message
,以及track
对象本身。
在track
对象内部,我们想要id
和numberOfViews
。查看我们正在更新的视图次数,我们希望在突变成功后看到更新的新值。该id
将由我们的Apollo Client缓存使用,我们将在稍后的前端实现中对其进行介绍。

这个突变操作应如下所示:
mutation IncrementTrackViews($incrementTrackViewsId: ID!) {incrementTrackViews(id: $incrementTrackViewsId) {codesuccessmessagetrack {idnumberOfViews}}}
让我们先运行它!
在右侧,您可以看到我们期望的字段是:code
为200,success
标志为true
,message
表明成功,我们得到了更新后的track
。

当我们重复执行该突变时,我们可以看到视图次数会上升!
code
,success
和message
的值是从哪里来的?让我们看看当我们将incrementTrackViewsId
改为我们的笨拙字符串"DOESNTEXIST"时会发生什么。
{"incrementTrackViewsId": "DOESNTEXIST"}
当我们运行这个mutation时,我们看到响应的code
是404,success
为false
,并且消息message
说"无法找到具有指定ID的track"。此外,track
也被设置为null
,没有可用的数据。

code
和message
的值是从哪里来的?我们的mutation看起来很棒,并且正在按预期执行!现在是时候跳转到客户端了。
分享您对本课程的疑问和评论
您的反馈帮助我们改进!如果您遇到了问题或感到困惑,请告诉我们,我们将为您提供帮助。所有评论都是公开的,必须遵守 Apollo行为准则。请注意,已解决或处理过的评论可能会被删除。
您需要GitHub账户才能发表以下评论。还没有吗? 请在我们的Odyssey论坛上发帖。