使用afterRemote挂钩在远程方法上发送Loopback响应

时间:2015-04-07 07:34:12

标签: node.js email express loopbackjs strongloop

我正在尝试处理需要发送邮件的请求。为了响应请求而不等待邮件发送,我将在afterRemote挂钩上发送邮件。该方法似乎正确运行并且邮件已发送,但由于某种原因,cb函数未执行,因此客户端上的请求仍未得到答复。问题在于下面的代码,你可以看到我有console.log("Here");cb(null,{});并且第一个命令被执行,但不是第二个看起来。

  user.joinEntity = function(data, cb) {
    var loopbackCtx = user.app.loopback.getCurrentContext();
    var userId=loopbackCtx.accessToken.userId;
    if(false){
        cb( new Error("Cant join that Entity."),{});
    }else{
        user.find({where:{id:userId}},function(err,applicant_instance){
            if (err) cb(err,{});
            if(applicant_instance.length>0)
            user.find({where:{id:data.ownerId}},function(err,founder_instance){
                if (err) cb(err,{});
                if(founder_instance.length>0)
                user.app.models.EntityApplication.create({email:applicant_instance[0].email,userId:userId,EntityFounder:founder_instance[0].id,Entity:data.id,Status:"pending"},function(err,Entity_Application_Instance){
                    if (err) cb(err,{});
                    loopbackCtx.join_entity={applicant:applicant_instance[0].email,entity:data.name,to:founder_instance[0].email};
                    console.log("Here");
                    cb(null,{});
                });
            });
        })
    }
  }
  user.afterRemote('joinEntity',function(){
      var loopbackCtx = user.app.loopback.getCurrentContext();
      user.app.models.Email.send({
        to: loopbackCtx.join_entity.to,
        from: 'mailer@domain.org',
        subject: 'Application to enter your Entity',
        // text: '<strong>HTML</strong> tags are not converted'
        html: 'User <strong>'+loopbackCtx.join_entity.applicant+'</strong> wants to enter Entity by the name of <strong>'+loopbackCtx.join_entity.entity+'</strong>'
      }, function(err) {
        if (err) throw err;
        console.log('> email sent successfully');       
      });
  });

1 个答案:

答案 0 :(得分:1)

通常,您希望确保在远程挂钩上执行next()回调,以告知LB(或更确切地说)您希望此特定中间件允许继续处理。如果您不打电话给next(),那么您基本上会告诉Express这是中间件处理的结束。确保接受远程钩子的所有三个参数,然后在方法操作完成时执行next()

user.afterRemote('joinEntity',function(ctx, instance, next){
  // *** notice arguments above!

  var loopbackCtx = user.app.loopback.getCurrentContext();
  user.app.models.Email.send({
    to: loopbackCtx.join_entity.to,
    from: 'mailer@domain.org',
    subject: 'Application to enter your Entity',
    // text: '<strong>HTML</strong> tags are not converted'
    html: 'User <strong>'+loopbackCtx.join_entity.applicant+'</strong> wants to enter Entity by the name of <strong>'+loopbackCtx.join_entity.entity+'</strong>'

  }, function(err) {
    // *** notice the correct way to indicate an error!
    if (err) { next(err); }

    console.log('> email sent successfully');

    // *** Now tell Express to keep processing middleware
    next();
  });
});