Created
April 16, 2019 08:55
-
-
Save hzburki/bc5de24d948a373ad4ca68cf72514404 to your computer and use it in GitHub Desktop.
Re-usable database connections in serverless blog project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Sequelize = require('sequelize') | |
const sequelize = new Sequelize( | |
process.env.DB_NAME, | |
process.env.DB_USERNAME, | |
process.env.DB_PASSWORD, | |
{ | |
host: process.env.DB_HOST, | |
port: process.env.DB_PORT, | |
dialect: process.env.DB_DIALECT, | |
} | |
) | |
// Models | |
const User = require('./models/User')(sequelize, Sequelize) | |
const Post = require('./models/Post')(sequelize, Sequelize) | |
const Comment = require('./models/Comment')(sequelize, Sequelize) | |
/* The magic lies here */ | |
let connection= {} | |
let Models = { | |
User, | |
Post, | |
Comment | |
} | |
/** | |
* Creating Associations | |
*/ | |
Object.keys(Models).forEach(function(modelName) { | |
if (Models[modelName].associate) { | |
Models[modelName].associate(Models); | |
} | |
}) | |
module.exports = async () => { | |
if(connection.isConnected){ | |
console.log("use existing connection") | |
return Models | |
} | |
try { | |
await sequelize.sync() | |
await sequelize.authenticate() | |
connection.isConnected = true | |
console.log("use new connection") | |
return Models | |
} catch (error) { | |
console.log(`Connection Error: ${error}`) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment