GraphQL(8):与数据库结合示例

1 执行命令

npm install mysql -S

2 新建数据库表

DROP TABLE IF EXISTS `account`;
CREATE TABLE `account`  (
  `id` int(0) NOT NULL,
  `name` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `age` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `sex` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `department` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

3 代码实现

const express = require('express');
const {buildSchema} = require('graphql');
const grapqlHTTP = require('express-graphql').graphqlHTTP;
const mysql = require('mysql');
// https://www.npmjs.com/package/mysql
var pool = mysql.createPool({
    connectionLimit: 10,
    host: '192.168.222.156',
    user: 'root',
    password: '123456',
    database: 'db1'
});


// 定义schema,查询和类型, mutation
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
        deleteAccount(id: ID!): Boolean
        updateAccount(id: ID!, input: AccountInput): Account
    }
    type Query {
        accounts: [Account]
    }
`);

// 定义查询对应的处理器
const root = {
    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,
                        sex: results[i].sex,
                        age: results[i].age,
                        department: results[i].department,
                    })
                }
                resolve(arr);
            })
        })
    },
    createAccount({ input }) {
        const data = {
            name: input.name,
            sex: input.sex,
            age: input.age,
            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);
            })
        })
    },
    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', grapqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))

app.listen(3000);

启动后自行测试接口,这里就不一一测试了。

相关推荐
一只爱打拳的程序猿12 分钟前
【Spring】更加简单的将对象存入Spring中并使用
java·后端·spring
杨荧13 分钟前
【JAVA毕业设计】基于Vue和SpringBoot的服装商城系统学科竞赛管理系统
java·开发语言·vue.js·spring boot·spring cloud·java-ee·kafka
minDuck15 分钟前
ruoyi-vue集成tianai-captcha验证码
java·前端·vue.js
为将者,自当识天晓地。34 分钟前
c++多线程
java·开发语言
daqinzl42 分钟前
java获取机器ip、mac
java·mac·ip
激流丶1 小时前
【Kafka 实战】如何解决Kafka Topic数量过多带来的性能问题?
java·大数据·kafka·topic
Themberfue1 小时前
Java多线程详解⑤(全程干货!!!)线程安全问题 || 锁 || synchronized
java·开发语言·线程·多线程·synchronized·
时差9531 小时前
【面试题】Hive 查询:如何查找用户连续三天登录的记录
大数据·数据库·hive·sql·面试·database
让学习成为一种生活方式1 小时前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
晨曦_子画1 小时前
编程语言之战:AI 之后的 Kotlin 与 Java
android·java·开发语言·人工智能·kotlin