8. 定义Mmutation
在GraphQL中,GraphQL客户端(或外部方)使用mutation来修改数据集。
定义mutation与定义查询非常相似, 唯一的区别在于如何实现mutation里的逻辑。
现在让我们来实战一下吧。
准备工序
本课程是上一节“定义查询”的延续,我们默认你已经完成了这一课哦。
复制GraphQL Sandbox项目到本地:
git clone https://github.com/kadirahq/graphql-blog-schema.git
切换到defining-mutations
分支:
cd graphql-blog-schema
git checkout defining-mutations
安装依赖项并启动沙箱:
npm install
npm start
现在就可以在本地访问GraphQL Sandbox啦,浏览器里输入地址:http://localhost:3000
这个沙箱的schema看起来很像我们在前几堂课中使用的schema,但它是一个缩小版本(与我们在上一课中创建的schema非常相似)。
你可以通过阅读repo中的src/schema.js
来了解它。 我们将在schema.js里编写相关代码。
你好,mutation
现在让我们来编写第一个mutation,它的功能是添加一个新的帖子到我们的博客中。下面是调用这个mutation的请求:
mutation insertFirstPost {
post: createPost(
title: "GraphQL is Awesome",
content: "Yep, it's purely awesome."
) {
_id,
title
}
}
从上可知,定义mutiation就同定义根查询里的一个字段一样。 具体如下:
const Mutation = new GraphQLObjectType({
name: "BlogMutations",
description: "Mutations of our blog",
fields: () => ({
createPost: {
type: Post,
args: {
title: {type: new GraphQLNonNull(GraphQLString)},
content: {type: new GraphQLNonNull(GraphQLString)}
},
resolve: function(source, args) {
let post = Object.assign({}, args);
// Generate the _id
post._id = `${Date.now()}::${Math.ceil(Math.random() * 9999999)}`;
// Assign a user
post.author = "arunoda";
// Add the Post to the data store
PostsList.push(post);
// return the new post.
return post;
}
}
})
});
在resolve
函数里,我们简单的添加了一个新的帖子到PostList
数组中并返回它。
现在需要将这个mutation分配给我们的schema,更新一下schema吧:
const Schema = new GraphQLSchema({
query: Query,
mutation: Mutation
});
很简单吧? 现在试试调用下面的mutation:
mutation insertFirstPost {
post: createPost(
title: "GraphQL is Awesome",
content: "Yep, it's purely awesome."
) {
_id,
title
}
}
你可以通过查询schema来验证此帖是否添加成功哦。
现在有一个简单的任务考考你。
调用这个查询:
mutation insertFirstPost {
post: createPost(
title: "GraphQL is Awesome"
) {
_id,
title
}
}
`
会得到什么结果呢?
- Successfully added the post.
- Successfully added the post, but there is a warning stating that a content field is required.
- Got an error stating that a content field is required.
- Nothing happened, there was a JavaScript console error.
当我们调用该mutation时,会得到一个错误警告:content字段是必须的。 这是因为我们定义了mutiaon里的字段都是必须的。 请看:
const Mutation = new GraphQLObjectType({
...
args: {
title: {type: new GraphQLNonNull(GraphQLString)},
content: {type: new GraphQLNonNull(GraphQLString)}
},
...
});
最后
现在我们知道了如何在schema中定义一个mutation,它与根查询中字段的定义非常相似,不同的是mutation能改变你的底层数据集。
在mutation操作后,非常重要的一点是需要返回修改过的文档。你可以在之后的课程及Replay的学习中了解更多这方面的知识。