How can I switch a model's datasource in loopback more than once? attachTo is not working

334 Views Asked by At

I have a model that I need to switch dataSources whenever I want. For that, I created a remote method on that model and used the attachTo() method.

// myModel.js

 switchDataSource = function(req, fn){
 const app = MyModel.app;
 console.log('req.dataSource ', req.dataSource);

 if(req.dataSource === 'datasource1'){
  MyModel.attachTo(app.dataSources.datasource1);
 } else if(req.dataSource === 'datasource2'){
  MyModel.attachTo(app.dataSources.pagarmeTest);
 } 
 console.log('Datasource Attached: ', MyModel.getDataSource().settings.name);
 fn();
}

The first time I call the remote method the datasource is changed accordingly.

For example, datasource1 is attached to myModel, and now I call the remote method with datasource2. This will work just fine.

However, if I call this remote method, passing datasource1 - the one that was previously attached to myModel - it wont work. console.log(Model.getDataSource().settings.name) shows that the datasource has changed, however when I use the model and its datasource, it is still the previous one.

On datasources.local.js, I have declared the datasources which I will be constantly attaching and detaching from my model Model.

// datasources.local.js

exports.datasource1 = {
  name: 'datasource1',
  connector: 'rest',
  ...
}

exports.datasource2 = {
  name: 'datasource2',
  connector: 'rest',
  ...
}

So it seems that I cannot change the datasource to a datasource that has been used previously by the same model... I noticed that the problem is not switching to a new dataSource, but instead trying to attach a datasource that had been attached before by the same Model.

1

There are 1 best solutions below

1
On

Perhaps the best choice would be to reload all models. Is it possible to happen in loopback?