我在VerifyUserAccess
中制作了middleware
loopback
,如下所示:
module.exports = function(options) {
return function storeCurrentUser(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.'));
}
const LoopBackContext = require('loopback-context');
const loopbackContext = LoopBackContext.getCurrentContext();
if (loopbackContext) {
loopbackContext.set('currentUser', user);
}
next();
});
};
};
我还在middleware.json
添加了它,如下所示:
...
"initial": {
"./middleware/verify_user_access": {},
...
}
...
但问题是我总是loopbackContext
null
。
第二个问题是如何访问currentUser
会导致API
。我在下面做了:
Gameversionandtype.GetGameversionandtypeByGameTypeID = (ctx, callback) =>
{
const LoopBackContext = require('loopback-context');
const context = LoopBackContext.getCurrentContext();
const currentUserResult = context && context.get('currentUserResult');
console.log('currentUser.username: ', currentUserResult.id);
...
...
}
请告诉我如何设置currentUser
结果以及如何在API
中获取结果。我也提到了文档loopback-context
npm
模块,但我找不到任何解决方案。提前感谢你。