Skip to content

Instantly share code, notes, and snippets.

@hzburki
Created April 16, 2019 08:55
Show Gist options
  • Save hzburki/bc5de24d948a373ad4ca68cf72514404 to your computer and use it in GitHub Desktop.
Save hzburki/bc5de24d948a373ad4ca68cf72514404 to your computer and use it in GitHub Desktop.
Re-usable database connections in serverless blog project
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