简体   繁体   English

如何在环回中以编程方式更改DataSource

[英]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. 我想当任何用户登录回送时,根据存储在User模型中的用户连接字符串更改数据集。

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: 我在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? 有解决这个问题的主意吗?

You can use attachTo() function to attach a datasource based on conditions. 您可以使用attachTo()函数根据条件附加数据源。

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. 还要使用已定义的数据源,即datasource.json中的内存

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

Please refer this too: app.models() 请也参考此: app.models()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM