【发布时间】:2015-02-02 02:55:54
【问题描述】:
也许我想得不够努力,但可以说我有 99% 相似的代码,为它构建函数的最小方法是什么?
// this is just an express route, not the function I am building
// doPay() is the function I am trying to build properly
function(req,res) {
if(req.user) {
// I can use req.user.id in my function
doPay(req,res);
} else {
passport.authenticate('local-signup', function(err, user, info) {
// instead of req.user.id I would just need user.id
doPay();
});
}
}
doPay()
// My doPay() function, above I need to pass either req.user.id or user.id
// based on the boolean, so how do I adjust this to adapt to that?
gateway.customer.find(req.user.id, function(err, customer) {
//do payment stuff for an existing user, if the user is new I need to use
//user.id above
});
【问题讨论】:
-
只需给
doPay一个id的参数? -
我确实认为它很简单,不是吗。我刚醒来,需要更多的咖啡..
-
我没有使用过护照,所以我不知道它是如何工作的,但通常你会有类似:
.get( authModule(options), function(req, res) { doPay(req.user) });和authModule会注意用户是否是auth 并且具有正确的权限,或者是否需要显示登录屏幕或错误页面。 -
是的,这就是将它用作中间件,正确的。由于我想要实现的目标的性质,我不会那样做。
-
好的,所以在
passport.authenticate之后回调的user实际上是属于请求的。那么,您为什么不为第一种情况执行 a)doPay(req, res, req.user);而为第二种情况不执行doPay(req, res, user);的原因是什么。还是 b) 在调用doPay(req,res);之前的第二种情况下的req.user = user;?我实际上看不出doPay函数需要做这种决定的原因,因为在你调用的地方更明显。
标签: javascript node.js function express