【问题标题】:How to Fetch MySQL all table data using GraphQL如何使用 GraphQL 获取 MySQL 所有表数据
【发布时间】:2019-01-30 17:25:46
【问题描述】:

我是 GraphQL 的新手,所以我想在 Express 服务器中获取 MySQL 的所有表数据,然后将其推送到 ReactJS。我该怎么做?

【问题讨论】:

    标签: mysql reactjs express graphql


    【解决方案1】:

    将 Knex 连接到 (db/db.js) 中的数据库:

    const config = require('../../config/config');
    const knex = require('knex')(config.config);
    
    module.exports = knex;
    

    需要 GraphQL 和 Knex (DB):

    const graphql = require('graphql');
    const knex = require('./db/db');
    
    const { 
        GraphQLObjectType, 
        GraphQLString, 
        GraphQLSchema,
        GraphQLID,
        GraphQLInt,
        GraphQLList,
        GraphQLNonNull
     } = graphql;
    

    假设您有一种图书类型:

    // Your book type
    const BookType = new GraphQLObjectType({
        name: 'Book',
        fields: () => ({
            id: { type: GraphQLID },
            name: { type: GraphQLString },
            genre: { type: GraphQLString },
        })
    });
    
    // Prepare query to get all books, I used Knex query builder with MySQL
    const RootQuery = new GraphQLObjectType({
        name: 'RootQueryType', 
        fields: {
            books: {
                type: new GraphQLList(BookType),
                async resolve(parent, args){
                  const books = await knex('books');
                  return books;
                }
            },
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-09
      • 2017-05-04
      • 2017-09-19
      • 2018-06-30
      • 2020-11-28
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      相关资源
      最近更新 更多