Multiple database switching dynamic in node-express

i have searched lot to get a solution to my problem. but didn't got it. if anyone have the experience in such situations please help me.

i have created a application server in node express with MySQL a database. and successfully create REST API endpoints which works successfully.

but our projects scaled up. a new client approaches so we need to serve those clients too. those client may have 1k users.but the database schema is same.

solution 1: create a separate server and database for each client with different port no. but i don't think this is good solution because if we have 100 client we can't maintain the code base.

solution 2: create a separate database for each client and switch database connection at run time. but i don't understand how to implement solution 2. any suggestion highly appreciated.

if more than one client requesting same server how to know which database need to connect using the endpoint URL. i there any alternate way to tackle this situation.

my solution: create a middle ware to find out the which database is required and return the connection string.is it good idea.

middleware. in below example i use JWT token which contain database name.

const dbHelper=new db();

class DbChooser {

constructor(){
this. db=
    {
        wesa:{
            host: "xxx",
            user: "xxxx",
            password: "xxxxx",
            database: "hdgh",
            connectionLimit:10,
            connectTimeout:30000,
            multipleStatements:true,
            charset:"utf8mb4"
        },
        svn:{
            host: "x.x.x.x.",
            user: "xxxx",
            password: "xxx",
            database: "xxx",
            connectionLimit:10,
            connectTimeout:30000,
            multipleStatements:true,
            charset:"utf8mb4"
        }

    };

}

async getConnectiontring(req,res,next){
//console.log(req.decoded);

let d=new DbChooser();
let con=d.db[req.decoded.userId];
console.log(mysql.createPool(con));
next();

}

} module.exports=DbChooser;

#javascript #node-js #angular #express

1 Likes15.20 GEEK