• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

362
Views
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 that

const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname')

and then declare your Model

const 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

about 3 years ago · Santiago Trujillo
3 answers
Answer question

0

You can achieve this with the beforeConnect hook, something like this:

 sequelize = new Sequelize(config.database, '', '', config); sequelize.beforeConnect(async (config) => { config.username = await getSecretUsername(); config.password = await getSecretPassword(); });

Leave the initial credentials empty, then use beforeConnect to mutate the configuration. I'm not sure if this is the cleanest way to use it, but it seems to be working.

https://sequelize.org/master/manual/hooks.html

about 3 years ago · Santiago Trujillo Report

0

To create an asynchronous function we use async

function after5Seconds() {

return new Promise(resolve => {

setTimeout(() => {

resolve('resolved');

}, 5000);

});

}

async function asyncCallMethod() {

console.log('calling');

const result = await after2Seconds();

console.log(result);

// se espera la respuesta: "resolved"

}

asyncCallMethod();

about 3 years ago · Santiago Trujillo Report

0

I found a 'pure' sequelize way to do this through lifecycle hooks:

Basically a generic setup in a db.js file would look like this:

const { Sequelize } = require('sequelize');
const asyncFetch = require('../util/async-fetch');

const sequelize = new Sequelize({
  dialect: 'mysql',
  database: 'db_name',
  host: '127.0.0.1'
});

sequelize.beforeConnect(async (config) => {
  const [username, password] = await Promise.all([
    asyncFetch('username'),
    asyncFetch('password')
  ]);
  config.username = username;
  config.password = password;
});

module.exports = sequelize;

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error