如何在Node中创建可重用的函数而不编写样板代码
I am using Express.js as http server. Defined all my routes.
我使用Express.js作为http服务器。定义了我的所有路线。
Most endpoints need to verify session before returning a response. E.g. below code serves users in the system and list of services respectively:
大多数端点需要在返回响应之前验证会话。例如。下面的代码分别为系统中的用户和服务列表提供服务:
function getUsers(req, res, next) {
verifyUser(req, res, next, function () {
//serve users
});
}
function getServices(req, res, next) {
verifyUser(req, res, next, function () {
//serve services
});
}
You probably noticed there is a verifyUser function which validates the session. Which is as below.
您可能已经注意到有一个验证会话的verifyUser函数。如下所示。
function verifyUser(req, res, next, callback) {
var sessionKey = req.cookies.sessionKey;
var user = users.userBySession(sessionKey);
if (user) {
callback(req, res, next, user);
} else {
res.status(401).send({
message: 'Unauthorized'
});
}
}
As you can see I keep passing in req, res and next parameters along with a callback whenever I use this function.
正如您所看到的,每当我使用此函数时,我会继续传递req,res和next参数以及回调。
I tried to use apply function to make it easier. Changed my getUsers function like this:
我尝试使用apply函数使其更容易。改变了我的getUsers函数,如下所示:
function getUsers(req, res, next) {
verifyUser
.apply(null, arguments, function () {
//serve users
});
}
The problem with this approach is callback is not passed into verifyUser function. And I don't really like passing null as scope with each call.
这种方法的问题是回调没有传递给verifyUser函数。而且我不喜欢在每次调用时将null作为范围传递。
How can I achieve this by writing less and better code ? Any ideas?
如何通过编写更少和更好的代码来实现这一目标?有任何想法吗?
2 个解决方案
#1
0
You could use bind
to create a 'partial function':
您可以使用bind来创建“部分函数”:
// create bound responseHelper object
var responseHelper = verifyUser.bind(null, req, res, next);
// usage
responseHelper(getUsersCallback); // same as verifyUser(req, res, next, getusersCallBack);
更多相关文章
- 如何在SOF上的新帖子中没有像“Grippie”这样的'onclick'执行Jav
- 覆盖odoo 8中的JS函数
- JavaScript 函数柯里化(参考《JavaScript模式》)
- js中匿名函数的写法
- mongojs的异步调用找到函数
- 在JavaScript中的for循环中调用异步函数
- Javascript学习之匿名函数与自执行详解
- 第三节(JavaScript 对象、日期,函数)
- 用javaScript编写的验证函数只运行一次?