Vulcan/packages/nova-voting/lib/vote.js

94 lines
2.3 KiB
JavaScript
Raw Normal View History

2016-01-02 18:41:45 +01:00
// The equation to determine voting power. Defaults to returning 1 for everybody
Telescope.getVotePower = function (user) {
return 1;
};
2016-01-03 18:18:09 +01:00
Telescope.operateOnItem = function (collection, itemId, user, operation) {
user = typeof user === "undefined" ? Meteor.user() : user;
2016-01-03 18:18:09 +01:00
var item = collection.findOne(itemId);
2016-01-02 18:41:45 +01:00
var votePower = Telescope.getVotePower(user);
2016-01-03 18:18:09 +01:00
var hasUpvotedItem = user.hasUpvotedItem(item);
var hasDownvotedItem = user.hasDownvotedItem(item);
var update = {};
// console.log(collection)
// console.log(item)
// console.log(user)
// console.log(operation)
// make sure item and user are defined, and user can perform the operation
if (
!item ||
!user ||
!user.canVote() ||
operation === "upvote" && hasUpvotedItem ||
operation === "downvote" && hasDownvotedItem
) {
return false;
}
2016-01-02 18:41:45 +01:00
2016-01-03 18:18:09 +01:00
// ------------------------------ Sync Callbacks ------------------------------ //
item = Telescope.callbacks.run(operation, item, user);
2016-01-03 18:18:09 +01:00
switch (operation) {
2016-01-03 18:18:09 +01:00
case "upvote":
2016-01-03 18:18:09 +01:00
if (hasDownvotedItem) {
Telescope.operateOnItem(collection, itemd, user, "cancelDownvote");
}
update = {
$addToSet: {upvoters: user._id},
$inc: {upvotes: 1, baseScore: votePower}
}
break;
2016-01-03 18:18:09 +01:00
case "downvote":
2015-03-28 18:30:26 +09:00
2016-01-03 18:18:09 +01:00
if (hasUpvotedItem) {
Telescope.operateOnItem(collection, itemId, user, "cancelUpvote");
}
update = {
$addToSet: {downvoters: user._id},
$inc: {downvotes: 1, baseScore: -votePower}
}
break;
2016-01-03 18:18:09 +01:00
case "cancelUpvote":
2016-01-03 18:18:09 +01:00
update = {
$pull: {upvoters: user._id},
$inc: {upvotes: -1, baseScore: -votePower}
};
break;
2016-01-02 18:41:45 +01:00
2016-01-03 18:18:09 +01:00
case "cancelDownvote":
2016-01-03 18:18:09 +01:00
update = {
$pull: {downvoters: user._id},
$inc: {downvotes: -1, baseScore: votePower}
};
break;
}
2016-01-03 18:18:09 +01:00
update["$set"] = {inactive: false};
var result = collection.update({_id: item._id}, update);
if (result > 0) {
2016-01-03 18:18:09 +01:00
// extend item with baseScore to help calculate newScore
item = _.extend(item, {baseScore: (item.baseScore + votePower)});
2016-01-03 18:18:09 +01:00
// --------------------- Server-Side Async Callbacks --------------------- //
Telescope.callbacks.runAsync(operation+".async", item, user, collection, operation);
2016-01-03 18:18:09 +01:00
return true;
}
2016-01-02 18:41:45 +01:00
2016-02-18 12:16:32 +09:00
};