viam viam - 3 months ago 17
Node.js Question

How to change DataSource programmatically in loopback

Suppose each users has huge amount of data that no need to store those in single table. I want to store each user's data in separate database for faster query.

I want when any user logging in loopback, change datasets based on users connection strings that stored in User model.

I read all of loopback docs and try so many practice to do this but i can't implement this.

I try this in server/server.js:

app.use(loopback.context());
app.use(loopback.token());
app.use(function (req, res, next) {
if (!req.accessToken) {
return next();
}
app.models.User.findById(req.accessToken.userId, function(err, user) {
if (err) {
return next(err);
}
if (!user) {
return next(new Error('No user with this access token was found.'));
}
console.log('server.js');
var loopbackContext = loopback.getCurrentContext();
if (loopbackContext) {
loopbackContext.set('currentUser', user);
}

var DataSource = require('loopback-datasource-juggler').DataSource;
var ds = new DataSource('memory');
app.datasources.db= ds;// <----- IT DOES'NT WORKING
next();
});

});


but IT DOES'NT WORKING (marked in code).

Any idea to solve this issue?

Answer

You can use attachTo() function to attach a datasource based on conditions.

app.use(loopback.context());
app.use(loopback.token());
app.use(function (req, res, next) {
  if (!req.accessToken) {
    return next();
  }
  app.models.User.findById(req.accessToken.userId, function(err, user) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return next(new Error('No user with this access token was found.'));
    }
    //console.log('server.js');
    var loopbackContext = loopback.getCurrentContext();
    if (loopbackContext) {
      loopbackContext.set('currentUser', user);
    }
    // This way you can attach memory datasource to model.
    // This only covers models defined using app.model();
    var models = app.models();
    models.foreach(function(model) {
      model.attachTo(app.dataSources.memory);
    });
    next();
  });

});

Also use defined datasource, memory in datasource.json.

{
 "memory": {
    "name": "memory",
    "connector": "memory"
  }
}

Please refer this too: app.models()

Comments