如果您要问是否有一种方法可以将用户数据全球化,以便它可以神奇地用于您的所有方法,简短的回答是在 Node 中没有安全的方法来执行此操作(更不用说在 Sails.js 中了)。 Node 的单线程特性使得以这种方式维护状态是不可能的。
有些人在 Sails 中通过使用 globally-applied policy 查找用户并将其添加到请求中解决了这个问题:
// api/policies/fetch-user.js
module.exports = function fetchUserPolicy (req, res, next) {
// Get the user ID out of the session.
var userId = req.session.userId;
// If there's no user logged in, just continue.
if (!userId) { return next(); }
// Look up the user by ID.
User.findOne({id: userId}).exec(function(err, user) {
if (err) { return res.serverError(err); }
if (!user) { return res.serverError(new Error('Could not find user in session!')); }
// Add the user info to the request.
req.user = user;
// Continue the request.
return next();
});
};
此代码没有任何问题,但我们不建议这样做,因为最佳做法是仅将策略用于访问控制。相反,您可以在自定义 hook 中执行几乎完全相同的操作:
// api/hooks/fetch-user.js
module.exports = function fetchUserHook(sails) {
return {
// Add some routes to the app.
routes: {
// Add these routes _before_ anything defined in `config/routes.js`.
before: {
// Add a route that will match everything (using skipAssets to...skip assets!)
'/*': {
fn: function(req, res, next) {
// Get the user ID out of the session.
var userId = req.session.userId;
// If there's no user logged in, just continue.
if (!userId) { return next(); }
// Look up the user by ID.
User.findOne({id: userId}).exec(function(err, user) {
if (err) { return res.serverError(err); }
if (!user) { return res.serverError(new Error('Could not find user in session!')); }
// Add the user info to the request.
req.user = user;
// Continue the request.
return next();
});
},
skipAssets: true
}
}
}
};
};
无论哪种方式,您仍然需要将req 传递给任何想要使用获取的用户信息的方法。