【问题标题】:Writing a function to adapt for two different cases?编写一个函数来适应两种不同的情况?
【发布时间】: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


【解决方案1】:

这里有两种替代设计。

你可以让函数接受 3 个参数

function doPay(req, res, user)

然后在该功能中进行测试以选择可用的功能

var userId;
if (req && req.user && req.user.id) userId = req.user.id;
if (!userId && user && user.id) userId = user.id;
if (!userId) throw "error...";

或者您可以选择将第三个参数设为要使用的 userId

 function doPay(req,res,userId)

并将 userId 源逻辑放在路由代码中,而不是 doPay 代码中。 doPay 只会使用它被告知要使用的 userId。我认为这种设计是@Bergi 在第一条评论中所建议的。

【讨论】:

  • 是的,这基本上就是我所做的。当我可以的时候会检查这个
  • 在第二种情况下,发布的问题没有显示任何正在传递的参数。在这里你可以称它为doPay(null, res, user)
  • 感谢 Paul,但我仍然需要 req 获取其他信息。我不使用 req.user.id 的唯一原因是因为当用户通过身份验证时,用户对象尚未创建并且确实在身份验证方法中创建。
  • 好吧,如果 req.user 未定义,您仍然可以传递 req 并且上面的代码将选择 user.id 或抛出错误。无论如何,您正在尝试做的事情听起来可以按照这些思路解决如果您以后仍然卡住,也许您可​​以在那时得到更好的答案,因为会有更多关于要求的信息。
  • 哦,好的,谢谢保罗。一切正常,我只想避免重复代码,这样我就不会混淆自己,不希望在处理付款时发生这种情况。谢谢,祝你有美好的一天!
猜你喜欢
  • 2017-12-11
  • 1970-01-01
  • 2019-10-17
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2020-03-13
相关资源
最近更新 更多