Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure two different datasource for a model in Strongloop Loopback framework?

Our MySQL database are set up with Write clusters and Read clusters, is there a way to set up Strongloop Loopback Model (e.g. User) to Write to MySQL Host A and Read from MySQL Host B?

like image 733
Mian Leow Avatar asked Jul 01 '15 23:07

Mian Leow


2 Answers

Try to use attachTo() if you want to change datasource for a single model. For example

app.models.YourModel.attachTo(app.dataSources.readDS);
readData();
...
app.models.YourModel.attachTo(app.dataSources.writeDS);
writeData();

You will have to define readDS and writeDS datasources in your datasources.json file:

{
 "readDS": {
    "host": "hostA",    
    "database": "dbOnHostA",
    "username": "user",
    "password": "password",
    "name": "readDS",
    "connector": "mysql"
  },

 "writeDS": {
    "host": "hostB",
    "database": "dbOnHostB",
    "username": "user",
    "password": "password",
    "name": "writeDS",
    "connector": "mysql"
  }
}

Or you can create your datasources dynamically.

like image 166
A.Z. Avatar answered Oct 06 '22 23:10

A.Z.


In loopback 2.0, You can try overriding getDataSource method and based on context, you can return different dataSource. However in loopback 3.0, context has been removed, and options is not passed to getDataSource, so it will be a challenge to achieve perfection.

like image 23
Praveen Kumar Gulati Avatar answered Oct 06 '22 23:10

Praveen Kumar Gulati