Tuesday 31 March 2020

Sequelize with asynchronous configuration in nodejs

I have been bashing my head for days as I cannot find a valid example of async configuration in Sequelize.So as you may know, you can simply config a Sequelize instance like thatconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') and then declare your Modelconst User = sequelize.define('User', { // Model attributes are defined here firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING // allowNull defaults to true } }, { // Other model options go here }); However what happens when the db credentials comes from an external service?const credentials = await getDbCredentials(); const sequelize = new Sequelize({credentials}) since sequelize models creation are coupled with the instance creation (unlike many others ORMs) this becomes a big problem.​My current solution is the following:const Sequelize = require("sequelize"); // Models const { User } = require("./User"); const env = process.env.NODE_ENV || "development"; const db = {}; let sequelize = null; const initSequelize = async () => { if (!sequelize) { let configWithCredentials = {}; if (env === "production") { const credentials = await getDbCredentials(); const { password, username, dbname, engine, host, port } = credentials; configWithCredentials = { username, password, database: dbname, host, port, dialect: engine, operatorsAliases: 0 }; } const config = { development: { // Dev config }, production: configWithCredentials, }; sequelize = new Sequelize(config[env]); sequelize.authenticate().then(() => { console.log("db authenticated") }); }); } db.User = User; db.sequelize = sequelize; db.Sequelize = Sequelize; }; initSequelize().then(() => { console.log("done"); }); module.exports = db; ​However I feel that this is not a good approach because of the asynchronous nature of the initialization and sometimes the `db` is undefined.Is there a better way to approach this thing?Thanks

Submitted March 31, 2020 at 10:26AM by madeo_

No comments:

Post a Comment