-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Closed
Description
UPDATE 2016-12-22 We ended up implementing a different solution as described in #3023.
Tasks
- Make the change in the
master
branch - see Inject remoting context to options arg #3023 (released in[email protected]
) - Back-port to
2.x
- see Inject remoting context to options arg [2.x] #3048 (released in[email protected]
) - Update the documentation - see Rework current-context docs loopbackio/loopback.io#227
- Close other context-related issues and point users to this new solution.
Original description for posterity
The example below allows you to inject the remote context object (from strong remoting) into all methods that accept an options
argument.
function inject(ctx, next) {
var options = hasOptions(ctx.method.accepts) && (ctx.args.options || {});
if(options) {
options.remoteCtx = ctx;
ctx.args.options = options;
}
next();
}
app.remotes().before('*.*', inject);
app.remotes().before('*.prototype.*', function(ctx, instance, next) {
inject(ctx, next);
});
// unfortunately this requires us to add the options object
// to the remote method definition
app.remotes().methods().forEach(function(method) {
if(!hasOptions(method.accepts)) {
method.accepts.push({
arg: 'options',
type: 'object',
injectCtx: true
});
}
});
function hasOptions(accepts) {
for (var i = 0; i < accepts.length; i++) {
var argDesc = accepts[i];
if (argDesc.arg === 'options' && argDesc.injectCtx) {
return true;
}
}
}
Why? So you can use the remote context in remote methods, operation hooks, connector implementation, etc.
MyModel.observe('before save', function(ctx, next) {
console.log(ctx.options.remoteCtx.accessToken.userId); // current user
});
This approach is specifically designed to allow you to do what is possible with loopback.getCurrentContext()
but without the dependency on cls
. The injection approach is much simpler and should be quite a bit faster since cls
adds some significant overhead.
bostondv, hgajula-applaud, airbinder and sqlwwx