sysgears / apollo-universal-starter-kit

Apollo Universal Starter Kit is a SEO-friendly, fully-configured, modular starter application that helps developers to streamline web, server, and mobile development with cutting-edge technologies and ultimate code reuse.
https://apollokit.org
MIT License
1.68k stars 323 forks source link

Add sequelize support #300

Open sakhmedbayev opened 7 years ago

sakhmedbayev commented 7 years ago

Would be nice if this starter kit or a branch of it supported sequelize or other SQL ORM.

Has someone accomplished it already?

larixer commented 7 years ago

For this enhancement to be possible we need someone to maintain this branch.

sakhmedbayev commented 7 years ago

@vlasenko, I would love to do it, but I am not sure if I qualify for the task at the moment. I am still learning javascript world :-)

I have managed to make some progress in that regard, however. I just followed a setup of sequelize withing Express application showing here. The most tricky part was models initialization. Here is how I accomplished it:

var Sequelize = require("sequelize");
var env = process.env.NODE_ENV || "development";

import configImp from 'pass/to/database/config.json'

const config = configImp[env]

if (process.env.DATABASE_URL) {
  var sequelize = new Sequelize(process.env.DATABASE_URL, config);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

let db = {};

// This part was difficult to figure out
let modules = [
  require('./user.js'),
];

// Initialize db
modules.forEach((module) => {
  const model = module(sequelize, Sequelize, config);
  db[model.name] = model;
});

// Apply associations
Object.keys(db).forEach((key) => {
  if ('associate' in db[key]) {
    db[key].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

export default db

And then in graphql middleware

import 'isomorphic-fetch';
import log from 'common/log';

import schema from '../api/schema';
import modules from '../modules';
import models from '../models';

import SECRET from '../secret'

export default graphqlExpress((req) => {
  try {
    return {
      schema,
      // context: modules.createContext()
      context: {
        modules: modules.createContext(),
        models: models,
        SECRET,
        user: req.user,
      }
    };
  } catch (e) {
    log(e.stack);
  }
});
larixer commented 7 years ago

@sakhmedbayev Pull Request is welcomed