graphql学习(二)

使用mutation修改数据

  1. 查询使用query,修改数据使用mutation
//修改的加input,来标识这个类型用来做输入的 
  input AccountInput {
name: String
age: Int
sex: String
department: String
salary: Int
}
//括号中的是形参,任意的 :后是类型
type Mutation {
createAccount ( input: AccountInput): Account
传递id,这个id是数据库中对应的那条要更新的
updateAccount(id: ID! , input: AccountInput): Account
}

服务端的修改接口

var express = require('express');
var {
    buildSchema
} = require('graphql')
const graphqlHTTP = require('express-graphql')
var app = express();
// 定义模型 修改 type不能丢 query相当与接口
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 {
       createdAccount(input:AccountInput):Account
       updateAccount(id:ID,input:AccountInput):Account
   }
   type Query {
       accounts:[Account]
   }
    `)
// 模拟定义一个数据库
const fakedDb = {}
// 定义修改对应的处理器
const root = {
    accounts: () => {
        //因为定义的accounts值是数组形式,但是如果直接返回修改后的数据库数据,他是对象形式会报错所以对象转数组
        var arr = [];
        for (const key in fakedDb) {
            arr.push(fakedDb[key])
        }
        // 返回数据库所有数据
        return arr;
    },
    createdAccount: ({
        input
    }) => {
        // input拿到了Account的所有字段然后赋值给了fakedb对象 相当于数据库的数据保存
        fakedDb[input.name] = input;
        // 返回保存的结果
        return fakedDb[input.name]
    },
    // 更新数据
    updateAccount: ({
        id,
        input
    }) => {
        // 拿到数据库中的数据把input新属性赋值给他,使用object.assign吧第二三个的值copy给第一个,第一个值就有了二三的属性
        const updateAccount = Object.assign({}, fakedDb[id], input);
        // 数据库中的数据变为修改后的内容
        fakedDb[id] = updateAccount;
        return updateAccount;
    }
}
/* GET users listing. */
app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}));
app.listen(3002, () => {
    console.log("开启3002成功")
});
// 向外公开文件夹供用户访问静态资源index
app.use(express.static('public'))

结果:

在这里插入图片描述
查询
在这里插入图片描述
在这里插入图片描述
注意:
在使用mutation时,schema中必须要有一个query,不然看不到schema
这种错误是没有在后面定义对应里面的参数值在这里插入图片描述

这种错误,当时accounts定义的是数组,这里查询的需要的是数组,但是返回值的是对象,所以要把对象转为数组在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值