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
.
I have this in my 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
}));
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?
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"
}
}
]
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?
})
try this now :
you can set ctx value :
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' } );
}
it's get ctx value :
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
context store userId
and accesTokan
. in whole web you can access using ctx
it's work like session
in loopback
.