Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

424
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda