2019GraphQL入门到精通 https://www.bilibili.com/video/BV1Ab411H7Yv?from=search&seid=16813706797539177189
视频 6
使用Mutations修改数据
// grphQL 要去Query是必须存在的
// 查询类型
// 输入类型
const express = require('express');
const graphqlHTTP = require('express-graphql');
const {buildSchema} = require('graphql');
// 定义schema,查询和类型
const schema = buildSchema (`
input AccountInput { // 输入类型
name: String
age: Int
sex: String
department: String
}
type Account {
name: String
age: Int
sex: String
department: String
}
type Mutation { // 查询类型
createAccount(input: AccountInput): Account
updateAccount(id: ID!, input: AccountInput): Account
}
type Query { // grphQL 要去Query是必须存在的
accounts: [Account]
}
`);
const fakeDB = {
};
// 定义对应的处理器
const root = {
accounts() {
var arr = [];
for (const key in fakeDB) {
arr.push(fakeDB[key]);
}
return arr; //对象转为数组
},
createAccount({input}) {
// 相当于数据库保存
fakeDB[input.name] = input;
// 返回保存结果
return fakeDB[input.name];
},
updateAccount({id, input}) {
// 相当于数据库保存
const updatedAccount = Object.assign({}, fakeDB[id], input);
fakeDB[id] = updatedAccount;
// 返回保存结果
return updatedAccount;
}
}
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true /* true代表需要调试 */
}))
app.listen(3000);
运行步骤
1. node mutation.js
2. 打开浏览器,输入localhost:3000/graphql
3. 查询栏中输入查询、修改语句,并验证。(见上图)