Hi Wolfgang,
We used a similar approach without issue with the loopback context (also injected via middleware).
Initially, we had similar issues as you did. We realized that creating new datasources within getDataSource() was the cause for messing up the context:
IF we call new DataSource() or loopback.createDataSource() in our own .getDataSource(), it will cause any data that we injected earlier into LB context to be lost (can still getCurrentContext, but context seems to be a new one).
Here's what works for us for your reference:
Model.getDataSource = function(model) {
var nsContext = loopback.getCurrentContext();
var tenant = nsContext.get('tenantId');
// Model.app.dataSources.trap - write to this ds when unable to switch to right tenant ds
var ds = Model.app._dsCache[tenant] ? Model.app._dsCache[tenant].ds : Model.app.dataSources.trap;
Model.attachTo(ds);
// switch all related models to same dataSource
var relation = Model.relations;
for (var relatedModel in relation) {
var model = Model.app.models[relation[relatedModel].modelTo.modelName];
model.attachTo(ds);
}
return ds;
};
For now, we pre-create dataSources for each tenant and cache into app._dsCache in server.js (temporary solution), so that we don't have to call new DataSource() anywhere along the middleware chain.
We are still trying to figure out a better solution/place to create the tenant dataSource. Any suggestions?
Hope this helps. Cheers!