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);

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

相关推荐
FF在路上12 分钟前
Knife4j调试实体类传参扁平化模式修改:default-flat-param-object: true
java·开发语言
真的很上进19 分钟前
如何借助 Babel+TS+ESLint 构建现代 JS 工程环境?
java·前端·javascript·css·react.js·vue·html
m0_7482338823 分钟前
SQL语句整理五-StarRocks
数据库·sql
州周34 分钟前
Ftp目录整个下载
linux·服务器·数据库
码农君莫笑38 分钟前
使用blazor开发信息管理系统的应用场景
数据库·信息可视化·c#·.net·visual studio
NiNg_1_2341 小时前
Echarts连接数据库,实时绘制图表详解
前端·数据库·echarts
众拾达人1 小时前
Android自动化测试实战 Java篇 主流工具 框架 脚本
android·java·开发语言
皓木.1 小时前
Mybatis-Plus
java·开发语言
不良人天码星1 小时前
lombok插件不生效
java·开发语言·intellij-idea
Azoner1 小时前
postgresql安装部署(linux)
数据库·postgresql