Sameer
Sameer

Reputation: 3526

Connect mysql database based on route in express.js with sequelize

I am building Multi tenant application, where each client has separate database.

Is it possible to change the database connection in sequelize depending on the route?

I have two routes

  1. scale.com/ss94545

  2. scale.com/mn94545

Upon login, users are redirected to scale.com/ss94545, to get all their data for their particular site.

The other mn94545 site uses a separate database and thus if they want to get all their data they have to go to scale.com/mn94545.

Every installation has its own database, and all databases have the same schema.

Is it possible to change the database connection depending on which route is visited?

This my basic static sequelize data connection:

const sequelize = new Sequelize('ss94545', 'root', 'root', {
  host: '127.0.0.1',
  port: 3306,
  dialect: 'mysql',
  logging: false,
});

Upvotes: 1

Views: 798

Answers (1)

Will
Will

Reputation: 19

Have you tried making the database name a route param and then instantiating sequelize after that? Assuming you might be using express it would go something like this...

app.get('/:dbname', function(req, res) {
  const sequelize = new Sequelize(req.params.dbname, 'root', 'root', {
    host: '127.0.0.1',
    port: 3306,
    dialect: 'mysql',
    logging: false,
  });
  //insert sequelize code here
  res.send('test ' + req.params.dbname);
});

Upvotes: 1

Related Questions