在 GraphQL 中,我们基本上有两种类型的操作:查询和突变。虽然文档中对查询进行了很好的描述,并且有很多示例,但我很难理解如何执行突变。突变显然是更新方法。
我创建了非常简单的 Node.js 服务器:
var express = require("express");
var graphqlHTTP = require("express-graphql");
var graphql = require("graphql");
var inMemoryDatabase = require("./inMemoryDatabase").inMemoryDatabase;
var _ = require("lodash-node");
var userType = new graphql.GraphQLObjectType({
name: "User",
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString }
}
});
var queryType = new graphql.GraphQLObjectType({
name: "Query",
fields: {
user: {
type: userType,
args: {
id: { type: graphql.GraphQLString }
},
resolve: function(parent, { id }) {
return _.find(inMemoryDatabase, { id: id });
}
}
}
});
var mutationType = new graphql.GraphQLObjectType({
name: "Mutation",
fields: {
user: {
type: userType,
args: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString }
},
resolve: function(parent, { id, name }) {
var index = _.findIndex(inMemoryDatabase, { id: id });
inMemoryDatabase.splice(index, 1, { id: id, name: name });
return _.find(inMemoryDatabase, { id: id });
}
}
}
});
var schema = new graphql.GraphQLSchema({
query: queryType,
mutation: mutationType
});
var app = express();
app.use(
"/graphql",
graphqlHTTP({
schema: schema,
graphiql: true
})
);
var port = 9000;
if (process.env.PORT) {
port = process.env.PORT;
}
app.listen(port);
console.log("Running a GraphQL API server at localhost:" + port + "/graphql");
Run Code Online (Sandbox Code Playgroud)
内存数据库只是在 User 对象的数组中{id, name}:
var inMemoryDatabase = [
{
id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8",
name: "Mark"
},
{
id: "2fb6fd09-2697-43e2-9404-68c2f1ffbf1b",
name: "Bill"
}
];
module.exports = {
inMemoryDatabase
};
Run Code Online (Sandbox Code Playgroud)
执行查询以通过 id 获取用户如下所示:
{
user(id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8"){
name
}
}
Run Code Online (Sandbox Code Playgroud)
突变改变用户名会是什么样子?
@Austio 的答案非常接近,但正确的方法是:
mutation updateUser {
user(id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8", name: "Markus") {
id
name
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6357 次 |
| 最近记录: |