Simon
Simon

Reputation: 2538

Building a reputation/karma system in js

So here is what is tripping me up:

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

Answers (2)

Simon
Simon

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

balsick
balsick

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

Related Questions