Skip to content

Instantly share code, notes, and snippets.

@Shalomeev
Last active July 3, 2018 12:20
Show Gist options
  • Save Shalomeev/b95bceb8bfaab4101acfd3f8b6c54908 to your computer and use it in GitHub Desktop.
Save Shalomeev/b95bceb8bfaab4101acfd3f8b6c54908 to your computer and use it in GitHub Desktop.
Helps to use sequelize and postgresql in express-js.

db/config.js

module.exports = {
    username: 'postgres',
    password: 'password',
    database: 'diary',
    dialect: 'postgres',
    protocol: 'postgres',
    port: 5432,
    host: '127.0.0.1'
};

db/index.js

const Sequelize = require('sequelize');
const config = require('./config');

const sequelize = new Sequelize(
    config.database, 
    config.username, 
    config.password, 
    config
);

sequelize
    .authenticate()
    .then(() => {
        console.log('Connection to database has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

module.exports = { sequelize };

db/models/student.js

module.exports = (sequelize, DataTypes) => {
    const Student = sequelize.define('Student', {
        name:{
            type: DataTypes.STRING,
            allowNull: false
        }
    });

    Student.associate = (models) => {
        Student.belongsTo(models.Group, {
            foreignKey: 'group_id',
            as: 'group'
        });
    };

    return Student;
};

db/models/group.js

module.exports = (sequelize, DataTypes) => {
    const Group = sequelize.define('Group', {
        name: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true
        }
    });

    Group.associate = (models) => {
        Group.hasMany(models.Student, {
            foreignKey: 'group_id',
            as: 'students'
        });
    };

    return Group;
};

db/models/index.js

const { sequelize } = require('./../index');
const models = [
    sequelize.import('./student'),
    sequelize.import('./group')
];

module.exports = initModels(sequelize);

function initModels(sequelize) {
    const result = {};
    models.forEach((model) => {
        result[model.name] = model;
    });

    Object.keys(result).forEach((modelName) => {
        if (result[modelName].associate) {
            result[modelName].associate(result);
        }
    });

    sequelize.sync();

    return result;
}

Then you can import models in your app like this:

const Group = require('./db/models/index').Group;
const Student = require('./db/models/index').Student;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment