GraphQL - Mutation修改数据

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. 查询栏中输入查询、修改语句,并验证。(见上图)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值