Page Contents

See also: See also: Example in LoopBack repository.

LoopBack应用有的时候需要一些上下文信息来实现一些业务逻辑,例如:

  • 获取当前的登录用户
  • 获取HTTP request(例如URL和headers)

一个典型的对模型方法的请求会超越多个层。不可能把所有的信息通过方法的参数一个个传递下去。

Configure context propagation

LoopBack上下文通过loopback.rest()中间件默认就被弃用了。可以在server/config.json文件里面对它进行配置:

"remoting": {
  "context": {
    "enableHttpContext": false
  },
  ...
}

使用当前上下文对象

一旦你启用了context,你可以通过使用loopback.getCurrentContext()来获取当前上下文对象。当前上下文可以在中间件,远程钩子,模型钩子,操作钩子和自定义方法中获得。

var count = 0;
MyModel.myMethod = function(cb) {
  var ctx = loopback.getCurrentContext();
  // Get the current access token
  var accessToken = ctx.get('accessToken');
  ...
  // Set more information to the current context
  ctx.counter = count++;
}

在远程方法中使用当前用户

The loopback.context() 被添加到loopback.rest()来确保所有的REST应用有当前上下文对象。 In advanced use cases, for example when you want to add custom middleware, you have to add the context middleware at the right position in the middleware chain (before the middleware that depends on loopback.getCurrentContext).

下面的例子使用中间件function来将当前的用户设置到上下文对象中去:

/server/server.js  Expand source

...
// -- Add your pre-processing middleware here --
app.use(loopback.context());
app.use(loopback.token());
app.use(function setCurrentUser(req, res, next) {
  if (!req.accessToken) {
    return next();
  }
  app.models.UserModel.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.'));
    }
    var loopbackContext = loopback.getCurrentContext();
    if (loopbackContext) {
      loopbackContext.set('currentUser', user);
    }
    next();
  });
});

// boot scripts mount components like REST API
...

/common/models/YourModel.js  Expand source

var loopback = require('loopback');
module.exports = function(YourModel) {
  ...
  //remote method
  YourModel.someRemoteMethod = function(arg1, arg2, cb) {
    var ctx = loopback.getCurrentContext();
    var currentUser = ctx && ctx.get('currentUser');
    console.log('currentUser.username: ', currentUser.username); // voila!
    ...
    cb(null);
  };
  ...
};