在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");
内存数据库只是位于一系列用户对象{id, name}
中:
var inMemoryDatabase = [
{
id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8",
name: "Mark"
},
{
id: "2fb6fd09-2697-43e2-9404-68c2f1ffbf1b",
name: "Bill"
}
];
module.exports = {
inMemoryDatabase
};
执行查询以按ID获取用户,如下所示:
{
user(id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8"){
name
}
}
更改用户名的样子如何?
答案 0 :(得分:2)
嘿可能会完全错过您在说的话,但是我对突变的看法是这样的
type
中指定的类型
var mutationType = new graphql.GraphQLObjectType({
name: "Mutation",
fields: {
user: {
// You must return something from your resolve function
// that will fulfill userType requirements
type: userType,
// with these arguments, find the user and update them
args: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString }
},
// this does the lookup and change of the data
// the last step of your result is to return something
// that will fulfill the userType interface
resolve: function(parent, { id, name }) {
// Find the user, Update it
// return something that will respond to id and name, probably a user object
}
}
}
});
然后将其作为上下文,您传递一些参数并请求返回用户
mutation updateUser {
user(id: "1", name: "NewName") {
id
name
}
}
在正常的生产模式中,通常还会有类似errors
之类的东西,可以针对失败/未找到情况返回以传达更新的不同状态
答案 1 :(得分:0)
@Austio的回答很接近,但是正确的方法是:
mutation updateUser {
user(id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8", name: "Markus") {
id
name
}
}