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

0

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

When you start the NodeJS server, the config.json configuration with the connection data is already loaded.

Banks have the same schema, they are the same in structure

The project has the default 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;
    
asked by anonymous 19.12.2018 / 18:17

0 answers