一、执行安装mysql命令:npm install mysql -S
const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-graphql');
const mysql = require('mysql');
// http://www.npmjs.com/package/mysql
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : '',
database : 'my_db'
});
// 定义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
deleteAccount(id: ID!): Boolean
}
type Query {
accounts: [Account]
}
`)
//定义查询对应的处理器
const root = {
//添加操作
createAccount({input}) {
const data = {
name: input.name,
age: input.age,
sex: input.sex,
department: input.department
};
return new promise((resolve, reject) => {
pool.query('insert into account set ?', data, (err) => {
if (err) {
console.log('出错了' + err.message);
return;
}
resolve(data);
})
})
},
// 更新操作
updateAccount({id, input}) {
const data = input;
return new promise((resolve, reject) => {
pool.query('update account set ? where name = ?', [data, id], (err) => {
if (err) {
console.log('出错了' + err.message);
return;
}
resolve(data);
})
})
},
// 查询操作
accounts() {
return new promise((resolve, reject) => {
pool.query('select name, age, sex, department from account', (err, results) => {
if (err) {
console.log('出错了' + err.message);
return;
}
const arr = [];
for (let i = 0; i < results.length; i++) {
arr.push({
name: results[i].name,
age: results[i].age,
sex: results[i].sex,
department: results[i].department
})
}
resolve(arr);
})
})
},
//删除操作
deleteAccount({id}) {
return new promise((resolve, reject) => {
pool.query('delete from account where name = ?', [id], (err) => {
if (err) {
console.log('出错了' + err.message);
reject(false);
return;
}
resolve(true);
})
})
}
}
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}))
app.listen(3000);