Browse Source

Commit 13-4: Better upvoting algorithm.

Frederic G. MARAND 9 years ago
parent
commit
16062d3698
1 changed files with 9 additions and 8 deletions
  1. 9 8
      lib/collections/posts.js

+ 9 - 8
lib/collections/posts.js

@@ -81,22 +81,23 @@ Meteor.methods({
       _id: postId
     };
   },
+
   upvote: function (postId) {
     check(this.userId, Match.OneOf(null, String));
     check(postId, String);
     if (this.userId === null) {
       throw new Meteor.Error('invalid', 'Not logged in');
     }
-    var post = Posts.findOne(postId);
-    if (!post) {
-      throw new Meteor.Error('invalid', 'Post not found');
-    }
-    if (_.include(post.upvoters, this.userId)) {
-      throw new Meteor.Error('invalid', 'Already upvoted this post');
-    }
-    Posts.update(post._id, {
+
+    var affected = Posts.update({
+      _id: postId,
+      upvoters: { $ne: this.userId }
+    }, {
       $addToSet: { upvoters: this.userId },
       $inc: { votes: 1 }
     });
+    if (!affected) {
+      throw new Meteor.Error('invalid', "You weren't able to upvote that post");
+    }
   }
 });