Reputation: 2538
So here is what is tripping me up:
When a user upvotes a post they get +2
karma.
When a user downvotes a post they get +2
karma.
When a user cancels/removes their vote they get -2
karma. (net 0)
The users post that was downvoted gets -2
karma.
The users post that was upvoted gets +2
karma.
When someone cancels/removes their vote the user that posted gets -2
if it was an upvote and +2
if it was a downvote.. (net 0)
I don't know if that makes sense, but essentially I want to reward people for casting a vote and punish people for creating bad posts..
Here is what I have:
In my database when a post gets an upvote this.userVote
is 1
, downvote is -1
and removing their vote is 0
.
upvote() {
let vote = this.userVote == 1 ? 0 : 1;
this.database.list('/upvotes/'+this.postData.id).set(this.userData.uid, vote)
}
downvote() {
let vote = this.userVote == -1 ? 0 : -1;
this.database.list('/upvotes/'+this.postData.id).set(this.userData.uid, vote)
}
So this works as intended and as I described above.
The problem is, I'm not sure how to set up the karma so that it works as intended.
I'm currently doing the following line to update the user karma as well as the posters karma:
this.database.database.ref('users/'+this.userData.uid).update({'karma': this.userKarma + karma}) //this.userKarma is the users karma
this.database.database.ref('users/'+this.postData.uid).update({'karma': this.postKarma + karma}) //this.postKarma is the karma of the user who created the post
How should I set up the variable karma
to be as I mentioned above..
Any advice? Thank you!
Upvotes: 0
Views: 170
Reputation: 2538
I ended up solving it like so:
getKarmaDelta(prevVote, vote) {
if((prevVote !== 1 && prevVote !== -1) && (vote === 1 || vote === -1)) {
this.updateUserKarma(2)
} else if (vote === 0) {
this.updateUserKarma(-2)
}
if(vote === -1 || (vote === 0 && prevVote === 1)) {
this.updatePosterKarma(-2)
} else if (vote === 1 || (vote === 0 && prevVote === -1)) {
this.updatePosterKarma(2)
}
}
Hope this helps someone else.
Upvotes: 0
Reputation: 1201
You could use Firebase Transaction system. Transactions are a way to atomically (there is no real atomicity in firebase) update data.
For example, to diminuish the karma by 1
this.database.database.ref('users/'+this.userData.uid).child('karma')
.transaction(function(karma){
if (!karma)
return 0;
return karma - 1;
});
Upvotes: 1