假设您有两个表:CARS
和VOTES
。
现在,您想使您的用户在汽车中投票。他们可以投票给新车,也可以更改以前的投票,但是没有用户可以两次投票给同一护理。
VOTE-MODEL
car_id
user_id
vote_value
您将如何为该模型设置UPSERT流程?请记住,UPSERT方法不接受远程挂钩(保存之前),这会阻止您获得user_id
访问令牌。
这是我尝试过的一些方法,但没有起作用:
尝试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);
});
}
}
}
});
};
尝试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执行代码。
它是命名的操作挂钩而不是远程钩。
顺便说一句,您的第一次尝试应该像:
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();
});
}
}
});
};
您只需修改用户ID,然后完成操作即可完成。无需进行额外的更新/UPSERT。
,如果不是新实例,请检查具有相同条件的先前投票,如果存在,则拒绝它,否则请允许它。
也有一个简单的解决方案,无需挂钩
Votes.vote = function(data, options, cb){
var userId = options && options.accessToken && options.accessToken.userId;
if(!userId){
return cb(UserNotFound); //return error
}
Votes.upsertWithWhere({
car_id: data.car_id,
user_id: userId
}, {
car_id: data.car_id,
user_id: userId,
vote_value: data.vote_value
}, function(err, result){
if(err) return cb(err);
cb(null, result);
});
};
Votes.remoteMethod('vote', {
accepts: [
{
arg: 'data',
type: 'Object',
required: true,
http: {source: 'body'}
},
{
arg: 'options',
type: 'Object',
http: "optionsFromRequest"
}
],
returns: {root: true, type: 'object'},
http: {verb: 'post', status: 201, path: '/vote'}
});