如何使用graphql获取mysql所有表数据

nzkunb0c  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(325)

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

vsnjm48y

vsnjm48y1#

将knex连接到db in(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;
            }
        },
    }
});

相关问题