How to change the connection to the database using Sequelize+Mysql+Express depending on the parameter sent in the request?

Asked

Viewed 186 times

0

For example, when receiving a request parameter equal to db1, in the precise controller that uses the db1 connection string

When starting the Nodejs server the configuration made in the config.json file with the connection data is already loaded

Banks have the same schema, they are equal in structure

The project has the standard structure created by Sequelize:

/Routes

/controllers

/models/index.js

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(`${__dirname}/../bin/configuration/config.json`)[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file =>
    (file.indexOf('.') !== 0) &&
    (file !== basename) &&
    (file.slice(-3) === '.js'))
  .forEach(file => {
    const model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

  • Almost: https://stackoverflow.com/questions/30202056/change-database-connection-depending-on-route-express-js-with-sequelize

  • I found something here that revolves: https://github.com/sequelize/sequelize/issues/3190

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.