Sometimes, we need to load database connection configuration asynchronously (for example loading env values from 3rd party secret store).
Sequalize doesn’t have such feature in the official documentation. But There is a possibility to use Sequelize.beforeConnect
hook.
You can initialize the Sequelize object with empty credentials and inside the beforeConnect
hook, you can load the env variables asynchronously and override the credentials.
const sequelize = new Sequelize('', '', '', { dialect: 'postgres' });
sequelize.beforeConnect(async (config) => {
const { host, database, username, password } = await getDbCredentials();
config.database = database;
config.username = username;
config.password = password;
config.host = host;
});
getDbCredentials()
is returning Promise and it fetches the DB credentials from remote API.