一、查詢使用query, 修改數據使用Mutation
image.png
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 = {};
//定義查詢對應的處理器
const root = {
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;
},
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);
測試界面.png