一、查詢使用query瘩缆, 修改數(shù)據(jù)使用Mutation
mutation.js
const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-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
}
// 使用Mutation時关拒,必須要有Query
type Query {
accounts: [Account]
}
`)
const fakeDB = {};
//定義查詢對應(yīng)的處理器
const root = {
createAccount({input}) {
// 相當于數(shù)據(jù)庫保存
fakeDB[input.name] = input;
//返回保存結(jié)果
return fakeDB[input.name];
},
updateAccount({id, input}) {
// 相當于數(shù)據(jù)庫的更新
const updatedAccount = Object.assign({}, fakeDB[id], input);
fakeDB[id] = updatedAccount;
// 返回保存結(jié)果
return updatedAccount;
},
accounts() {
var arr = [];
for (const key in fakeDB) {
arr.push(fakeDB[key]);
}
return arr;
}
}
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}))
app.listen(3000);