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


    1 执行命令

    npm install mysql -S

    2 新建数据库表

    1. DROP TABLE IF EXISTS `account`;
    2. CREATE TABLE `account` (
    3. `id` int(0) NOT NULL,
    4. `name` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
    5. `age` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
    6. `sex` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
    7. `department` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
    8. PRIMARY KEY (`id`) USING BTREE
    9. ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
    10. SET FOREIGN_KEY_CHECKS = 1;

    3 代码实现

    1. const express = require('express');
    2. const {buildSchema} = require('graphql');
    3. const grapqlHTTP = require('express-graphql').graphqlHTTP;
    4. const mysql = require('mysql');
    5. // https://www.npmjs.com/package/mysql
    6. var pool = mysql.createPool({
    7. connectionLimit: 10,
    8. host: '192.168.222.156',
    9. user: 'root',
    10. password: '123456',
    11. database: 'db1'
    12. });
    13. // 定义schema,查询和类型, mutation
    14. const schema = buildSchema(`
    15. input AccountInput {
    16. name: String
    17. age: Int
    18. sex: String
    19. department: String
    20. }
    21. type Account {
    22. name: String
    23. age: Int
    24. sex: String
    25. department: String
    26. }
    27. type Mutation {
    28. createAccount(input: AccountInput): Account
    29. deleteAccount(id: ID!): Boolean
    30. updateAccount(id: ID!, input: AccountInput): Account
    31. }
    32. type Query {
    33. accounts: [Account]
    34. }
    35. `);
    36. // 定义查询对应的处理器
    37. const root = {
    38. accounts() {
    39. return new Promise((resolve, reject)=>{
    40. pool.query('select name, age, sex, department from account', (err, results)=> {
    41. if(err) {
    42. console.log('出错了' + err.message);
    43. return;
    44. }
    45. const arr = [];
    46. for(let i=0;i<results.length;i++) {
    47. arr.push({
    48. name: results[i].name,
    49. sex: results[i].sex,
    50. age: results[i].age,
    51. department: results[i].department,
    52. })
    53. }
    54. resolve(arr);
    55. })
    56. })
    57. },
    58. createAccount({ input }) {
    59. const data = {
    60. name: input.name,
    61. sex: input.sex,
    62. age: input.age,
    63. department: input.department
    64. }
    65. return new Promise((resolve, reject)=>{
    66. pool.query('insert into account set ?', data, (err) => {
    67. if (err) {
    68. console.log('出错了' + err.message);
    69. return;
    70. }
    71. // 返回保存结果
    72. resolve(data);
    73. })
    74. })
    75. },
    76. updateAccount({ id, input }) {
    77. const data = input
    78. return new Promise((resolve, reject) => {
    79. pool.query('update account set ? where name = ?', [data, id], (err) => {
    80. if (err) {
    81. console.log('出错了' + err.message);
    82. return;
    83. }
    84. // 返回保存结果
    85. resolve(data);
    86. })
    87. })
    88. },
    89. deleteAccount({id}) {
    90. return new Promise((resolve, reject)=>{
    91. pool.query('delete from account where name = ?', [id], (err)=>{
    92. if(err) {
    93. console.log('出错了' + err.message);
    94. reject(false);
    95. return;
    96. }
    97. resolve(true);
    98. })
    99. })
    100. }
    101. }
    102. const app = express();
    103. app.use('/graphql', grapqlHTTP({
    104. schema: schema,
    105. rootValue: root,
    106. graphiql: true
    107. }))
    108. app.listen(3000);

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

  • 相关阅读:
    语音处理:Python实现dBFS刻度和采样值相互转换
    mybatis标签详解,一篇就够了
    MySQL同步数据到Elasticsearch
    当分布 非正态分布时,能否使用Pearson Correlation?
    Webpack 打包commonjs 和esmodule 模块的产物对比
    linux 监控CPU利用率
    Kubernetes控制平面组件:Scheduler调度器
    基于文本相似度的康复量表ICF映射研究
    设计模式-享元模式(Flyweight)
    MNN编译
  • 原文地址:https://blog.csdn.net/u013938578/article/details/139622811