Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

421
Vistas
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

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

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

over 4 years ago · Santiago Trujillo Denunciar

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();

over 4 years ago · Santiago Trujillo Denunciar

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;

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda