在mixins中获取用户代理和时区

时间:2019-05-20 04:58:18

标签: node.js loopback

我正在'create'挂钩上为模型创建mixin。我想访问用户代理和用户时区信息。

我也尝试使用LoopBackContext。但这并没有太大帮助,因为我找不到包含这些信息的对象。

var loopBackContext = require('loopback-context');

module.exports = function Request(Model, options) {
  Model.observe('access', function event(ctx, next) {
   var httpContext = loopBackContext.getCurrentContext();
    //access user-agent and timezone
    next();
  });
};

1 个答案:

答案 0 :(得分:0)

Please note that loopback-context does not work very reliably, we recommend to pass context via options object as explained in https://loopback.io/doc/en/lb3/Using-current-context.html.

The ctx argument passed to operation hooks like access is yet another type of a context object, see the docs on Operation hooks.

To access additional request headers, you should also override Model's createOptionsFromRemotingContext method, see https://loopback.io/doc/en/lb3/Using-current-context.html#override-createoptionsfromremotingcontext-in-your-model

module.exports = function Request(Model, options) {
  Model.createOptionsFromRemotingContext = function(ctx) {
    const base = this.base.createOptionsFromRemotingContext(ctx);
    return {
      ...base,
      userAgent: req.headers['user-agent'],
      // etc.
    };
  });

  Model.observe('access', function event(ctx, next) {
    const options = ctx.options || {};
    // options contains data created by Model.createOptionsFromRemotingContext
    // but only when invoked via REST API.
    // when called from JavaScript (e.g. from unit-tests), options are exactly
    // as provided by the caller (often undefined).
    const userAgent = ctx.options && ctx.options.userAgent;
    // access user-agent and timezone
    next();
  });
};