loopback3: associate users to different databases

92 Views Asked by At

I'm developing a project in loopback3 where I need to create accounts for multiple companies, where each compnay has its own database, I'm fully aware that the loopback3 docs has a section where they explain how to create datasources programmatically and how to create models from that datasource, and I've used that to create the following code which receives in the request a parameter which i called dbname and this one changes the linking to the wanted datasource..

userclinic.js

Userclinic.observe('before save', async (ctx, next) => {
    const dbname = ctx.instance.dbname; // database selection
    const dbfound = await Userclinic.app.models.Clinics.findOne({where:{dbname}}) // checking if that database really exist in out registred clients databases
    if( dbfound ){ // if database found
      await connectToDatasource(dbname, Userclinic) // link the model to that database
    } else { // otherwise
      next(new Error('cancelled...')) // cancel the save
    }
})

utils.js (from where i export my connectToDatasource method)

const connectToDatasource = (dbname, Model) => {
  console.log("welcome");
  var DataSource = require('loopback-datasource-juggler').DataSource;

  var dataSource = new DataSource({
      connector: require('loopback-connector-mongodb'),
      host: 'localhost',
      port: 27017,
      database: dbname
  });
  Model.attachTo(dataSource);
}

module.exports = {
  connectToDatasource
}

So my problem is that the datasource is actually really changing but the save happens in the previous datasource that was selected (which means it saves the instance to the old database) and doesn't save to the new one till I send the request again. so chaging the datasource is taking two requests to happen and it's also saving the instance in both databases.

I guess that when the request happen loopback checks the datasource related to that model first before allowing any action on that model, I really need to get this done by tonight and I wish someone can help out.

PS: if anyone has a solution to this or knows how to associate multiple clients (users) to multiple databases (programmatically of course) in any way using loopback 3 I'm all ears (eyes).

Thanks in advance.

0

There are 0 best solutions below