将会话存储在操作挂钩中-环回 [英] Store session in operation hook - Loopback

查看:74
本文介绍了将会话存储在操作挂钩中-环回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用express-session在Loopback应用程序中的after savebefore save操作挂钩中存储除userIdaccessToken以外的其他数据以存储在会话中.

I want to store some data other than userId or accessToken to store in a session, in after save or before save operation hook in Loopback application using express-session.

我的server/server.js中有此内容:

....
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
....

app.use(session({
    name:'session-name',
    secret: 'keyboard cat',
    store: new MongoStore({url: 'mongodb://localhost/test', ttl:1}),
    resave: false,
    saveUninitialized: true
}));

当我用一些参数定义远程方法时,它实际上是传递参数而不是req对象,所以我不能以明确的方式来做.

And as I'm defining the remote-method with some parameters it actually passing the parameter and not the req object, so I can't do it the express way.

如何使用会话来存储和获取价值?

How can I use the session to store and get value?

通过将其添加到我的model.json的remote-method中,我找到了一种在远程方法中设置会话的方法:

EDIT : I have found a way to set the session in remote method, by adding this to my model.json's remote-method :

"accepts": [
    {
        "arg": "req",
        "type": "object",
        "http": {
            "source": "req"
        }
    }
]

然后,将req参数添加到远程方法功能中,

And, adding the req parameter to the remote-method function,

Model.remoteMethod = function (req, callback) {
    req.session.data = { 'foo': 'bar' }
    callback(null)
};

现在,问题是我想在操作挂钩中获取此会话值

Now, the issue is I want to get this session value in operation hook

Model.observe('before save', function (ctx, next) {
    //How to get the session here?
})

推荐答案

尝试此操作 :

您可以设置ctx值:

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

    MyModel.myMethod = function(cb) {
      var ctx = LoopBackContext.getCurrentContext();
      // Get the current access token
      var accessToken = ctx && ctx.get('accessToken');
      ctx.set('xx', { x: 'xxxx' } );

    }

获得ctx值:

 module.exports = function(MyModel) {
      MyModel.observe('access', function(ctx, next) {
        const token = ctx.options && ctx.options.accessToken;
        const userId = token && token.userId;
        const modelName = ctx.Model.modelName;
        const scope = ctx.where ? JSON.stringify(ctx.where) : '<all records>';
        console.log('%s: %s accessed %s:%s', new Date(), user, modelName, scope);
        next();
      });
    };

loopback上下文存储userIdaccesTokan.在整个网络中,您可以使用ctx进行访问,就像loopback中的session一样.

loopback context store userId and accesTokan. in whole web you can access using ctx it's work like session in loopback.

这篇关于将会话存储在操作挂钩中-环回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆