How to access 'req' object in loopback from “access” hook?

白昼怎懂夜的黑 提交于 2020-01-16 09:04:58

问题


It seems operation hook "access" does not contains ctx.req object.

What i am trying to achieve is that session data should be available in all the models.

Session defined in middleware:

 "session": {
     "express-session": {
         "params": {
         "secret": "mysceret",
         "saveUninitialized": true,
         "resave": true
        }
    }
 }

In User.js :

req.session.user = userData; 

and to access session in Post model:

Post.observe('access', function(ctx, next) {     
   console.log('ctx.req : ' , ctx.req) // undefined
   ctx.query.filter = { tenantId: ctx.req.session.user.tenantId }; 
   // so cannot able to find session data here.   
   next();
}); 

Express-session : "express-session": "^1.15.6"

Loopback version : "loopback": "^3.0.0"

What I am missing or I am access session in a wrong way ? Please some help.

Thanks


回答1:


I'm going to heavily borrow from my answer at accessing current logged in user id in custom route in loopback

The operation hook context accepts what values you submit to it, as well as a few defaults related to the model, it would never have the userId by default. https://loopback.io/doc/en/lb3/Operation-hooks.html#operation-hook-context-object

The ctx in an operation hook is not the same as the ctx in a remote method.

If you want to pass in additional operation hook context values then you must use call a model method manually and send them as the second parameter.

model.create({color: 'red'}, {contextValue: 'contextValue', anotherContextValue: 'anotherContextValue'}, (err, obj) => {
   // Callback things...
}



回答2:


Operation hooks can read the accessToken from ctx.options provided you're logged in: https://loopback.io/doc/en/lb3/Using-current-context.html#access-the-context-from-operation-hooks

Model.observe('access', async ctx => {
  let {options: {accessToken = {}} = {}, ...otherAttributes} = ctx;
  console.log(accessToken);
});

You can even set some properties on the accessToken using a middleware hooked onto the "routes:before" section, since middlewares hace access to req and req.accessToken.

Your middleware could say something like:

module.exports = function() {
  return function setSession(req, res, next) {
    let {accessToken} = req;
    accessToken.session = req.session;
    next();
  };
};

however, if you're already doing:

 req.session.user = userData; 

To store the value of the current user onto the session, you can already access that using accessToken.user() wherever you can get a reference to the token in question.



来源:https://stackoverflow.com/questions/49886004/how-to-access-req-object-in-loopback-from-access-hook

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!