在Loopback上,如何在使用从访问令牌获取的user_id时执行Upsert事件?

时间:2017-03-09 23:28:17

标签: loopbackjs strongloop

假设您有两个表:CARSVOTES

现在您想让您的用户在汽车中投票。他们可以投票购买新车或更改他们之前的投票,但没有用户可以投票给同一个护理两次。

VOTE-MODEL

car_id

user_id

vote_value

您如何为该模型设置Upsert过程?请记住,Upsert方法不接受远程挂钩(保存前),这会阻止您从访问令牌中获取user_id

以下是我尝试过的一些方法,但没有奏效:

ATTEMPT 1

'use strict';
module.exports = function (Votes) {
  Votes.observe('before save', function setAutoData(context, next) {
    if (context.instance) {
      if (context.isNewInstance) {
        if (context.options.accessToken) {
          context.instance.user_id = context.options.accessToken.userId;
          Votes.upsertWithWhere({
            where: {
              car_id: context.instance.car_id,
              user_id: context.instance.user_id
            }
          }, context.instance, function (err, cb) {
            if (err) return next(err);
            console.log('cb', cb);
          });
        }
      }
    }
  });
};

ATTEMPT 2

'use strict';

module.exports = function(Votes) {

  Votes.observe('before save', function setAutoData(context, next) {
    if (context.instance) {
        if(context.isNewInstance) {

          if (context.options.accessToken) {

            context.instance.user_id = context.options.accessToken.userId;

            Votes.find({
              where: {
                car_id: context.instance.car_id,
                user_id: context.instance.user_id
              }
            }, function(err, cb) {
              if (!cb.length) {
                // If it does not find anything, go next, accept post
                next();
              } else {

                // Otherwise update record
                Votes.updateAll({
                  where: {
                    car_id: context.instance.car_id,
                    user_id: context.instance.user_id
                  }
                }, context.instance, function(err, cb) {
                  console.log('cb', cb);
                });

              }
            });

          }

        }
    }

  });

};

两次尝试的问题在于,似乎没有为Upsert或Udpate执行代码。

1 个答案:

答案 0 :(得分:1)

它的命名操作挂钩不是远程挂钩。

BTW你的第一次尝试应该像:

//Example JSRender loop
{{for myText}}
    <div>{{>city}}</div>
{{/for}}

您只需修改用户ID即可完成操作。无需额外更新/ upsert。

如果这不是新实例,请使用相同的标准检查以前的投票,如果它存在,则拒绝它,否则允许它。

也有一个简单的解决方案,无需挂钩

module.exports = function (Votes) {
  Votes.observe('before save', function setAutoData(context, next) {
    if (context.instance) {
      if (context.isNewInstance) {
        if (context.options.accessToken) {
          context.instance.user_id = context.options.accessToken.userId;          
        }
        return next();
      }else {
    Votes.count({
      where: {
        car_id: context.instance.car_id,
        user_id: context.instance.user_id,
        vote_value: context.instance.vote_value
      }
    }, function(err, count){
         if(err) return next(err);
             if(count > 0) next(SuitableError);
             next();
           });
      }
    }    
  });
};