As @ superhaw noted, each LoopBack model can only be connected to one data source.
You can create (subclass) a new model for each data source that you want to use. You can then either expose these models using data using unique REST URLs, or you can implement a wrapper model that will send methods to the correct model, depending on the data source.
In my example, I will show how to expose models with one data source for the Car
model, which is bound to db
and anotherdb
. The Car
model is defined in the usual way through common/models/car.json
and common/models/car.js
Now you need to define models for each data source:
// common/models/car-db.js { "name": "Car-db", "base": "Car", "http": { "path": "/cars:db" } } // common/models/car-anotherdb.js { "name": "Car-anotherdb", "base": "Car", "http": { "path": "/cars:anotherdb" } } // server/model-config.json { "Car": { "dataSource": "default" }, "Car-db": { "dataSource": "db" }, "Car-anotherdb": { "dataSource": "anotherdb" } }
You now have the following URLs:
GET /api/Cars:db GET /api/Cars:anotherdb GET /api/Cars
The solution described above has two limitations: you must define a new model for each data source, and the data source cannot be selected using the query parameter.
To fix this, you need a different approach. Once again, I assume that the Car
model is already defined.
Now you need to create a "dispatcher".
// common/models/car-dispatcher.json { "name": "CarDispatcher", "base": "Model", //< important! "http": { "path": "/cars" } } // common/models/car-dispatcher.js var loopback = require('loopback').PersistedModel; module.exports = function(CarDispatcher) { Car.find = function(ds, filter, cb) { var model = this.findModelForDataSource(ds); model.find(filter, cb); }; // a modified copy of remoting metadata from loopback/lib/persisted-model.js Car.remoteMethod('find', { isStatic: true, description: 'Find all instances of the model matched by filter from the data source', accessType: 'READ', accepts: [ {arg: 'ds', type: 'string', description: 'Name of the datasource to use' }, {arg: 'filter', type: 'object', description: 'Filter defining fields, where, orderBy, offset, and limit'} ], returns: {arg: 'data', type: [typeName], root: true}, http: {verb: 'get', path: '/'} }); // TODO: repeat the above for all methods you want to expose this way Car.findModelForDataSource = function(ds) { var app = this.app; var ds = ds && app.dataSources[ds] || app.dataSources.default; var modelName = this.modelName + '-' + ds; var model = loopback.findModel(modelName); if (!model) { model = loopback.createModel( modelName, {}, { base: this.modelName }); } return model; }; };
The final bit is removing Car
and using CarDispatcher
in the model configuration:
// server/model-config.json { "CarDispatcher": { dataSource: null, public: true } }