Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect GraphQL to MySQL

I've used express cli to set up a simple express project, And followed tutorials to create the db.js and schema.js but at this point I cant think of anyway to debug this error / to view any part of the schema in graphiql documentation.

{
  "errors": [
    {
      "message": "Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory."
    }
  ]
}

App.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var schema = require('./schema');
var graphqlHTTP = require('express-graphql');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

app.use('/api', graphqlHTTP({schema, graphiql: true}));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development'
        ? err
        : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

db.js

var Sequelize = require('sequelize');
var mysql = require('mysql');
var _ = require('lodash');

var Conn = new Sequelize('DB', 'Username', 'password', {
    host: 'DB IP',
    dialect: 'mysql'
});

var Sectors = Conn.define('sectors', {
    name: {
        type: Sequelize.STRING,
        allowNull: false
    }
});

Sectors.sync({force: true}).then(function () {
  // Table created
  return Sectors.create({
    name: 'test'
  });
});

exports.default = Conn;

Schema.js

var {
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLID,
    GraphQLString,
    GraphQLInt,
    GraphQLBoolean,
    GraphQLList,
    GraphQLNonNull
} = require('graphql');

var Db = require('./db');

var Sectors = new GraphQLObjectType({
  name: 'sectors',
  description: 'list of all the sectors',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve (sectors) {
          return sectors.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve (sectors) {
          return sectors.name;
        }
      }
    };
  }
});

var Query = new GraphQLObjectType({
  name: 'Query',
  description: 'Root query object',
  fields: () => {
    return {
      sectors: {
        type: new GraphQLList(Sectors),
        args: {
          id: {
            type: GraphQLInt
          },
          name: {
            type: GraphQLString
          }
        },
        resolve (root, args) {
          return Db.models.sectors.findAll({ where: args });
        }
      }
    };
  }
});

var Schema = new GraphQLSchema({query: Query});
exports.default = Schema;
like image 625
Ash Avatar asked Mar 20 '17 12:03

Ash


People also ask

Can I use GraphQL with MySQL?

You can integrate data from any type of backend into a GraphQL layer, making this advantage accessible to any type of project. Today, we'll take a look at how to integrate a GraphQL API and MySQL database in your GraphQL layer. As a result, a developer can access data from two different backends in a single query!

Can GraphQL connect to database?

Your GraphQL API can interact with any combination of data sources. Apollo provides a DataSource class that we can extend to handle interaction logic for a particular type of data source. In this section, we'll extend DataSource to connect both a REST API and a SQL database to Apollo Server.

Can I use GraphQL with SQL Server?

Hasura allows connecting to a SQL Server database and build a GraphQL API based on the database schema.


1 Answers

aha, the reason is exports wrong

exports.default = Schema

like this

module.exports = Schema
like image 118
ppy Avatar answered Oct 06 '22 01:10

ppy