a.dibacco
a.dibacco

Reputation: 490

Atomically incrementing a shared counter in Firebase realtime database

I need to decrement a counter (named credits) stored in Firebase real time database.

To decrement the counter I do like this:

var ref = admin.database().ref('licenseCredits/' + name + '/credits');

ref.transaction( (value) => {

  if (value === null) {
    return 0;
  } else if (typeof value === 'number') {

    return value - 1;
  } else {
    console.log('The counter has a non-numeric value: '); 
  }
});

The credits field is being correctly decremented. I put this code into a callable function but I don't know how to return the decremented value to the caller. If I simply return the ref.transaction result I get a "Unhandled RangeError exception".

Upvotes: 0

Views: 1824

Answers (2)

a.dibacco
a.dibacco

Reputation: 490

At the end I found a way to tackle the problem taking into account @chris answer.

I used a javascript promise implemented using the 'kew' library.

Here is the working code:

   var qTrans = Q.defer();

    var ref = admin.database().ref('licenseCredits/' + name + '/credits');
    var credits = 0;



    ref.transaction( (value) => {

      if (value === null) {
        // the counter doesn't exist yet, start at one
        return 1;
      } else if (typeof value === 'number') {
        // increment - the normal case
        return value + 1;
      } else {
        // we can't increment non-numeric values
        console.log('The counter has a non-numeric value: ' + JSON.stringify(value));
        // letting the callback return undefined cancels the transaction
      }
    }, (error, committed, snapshot) => {
        if (error) {
            console.log('Transaction failed abnormally!', error);
            qTrans.reject(error);

        } else if (!committed) {
            console.log('We aborted the transaction.');
            qTrans.reject(error);

        } else {
            console.log('Success!');
            console.log("Credit data: ", snapshot.val());
            qTrans.resolve(snapshot.val());

        }
    });

    return qTrans.promise;

Upvotes: 1

chris
chris

Reputation: 184

As per the documentation below, the there should be a onComplete function implemented.

https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction

var ref = admin.database().ref('licenseCredits/' + name + '/credits');
ref.transaction( (value) => {

    if (value === null) {
        return 0;
    } else if (typeof value === 'number') {
        return value - 1;
    } else {
        console.log('The counter has a non-numeric value: '); 
    }
}, function(error, committed, snapshot) {
    if (error) {
        console.log('Transaction failed abnormally!', error);
    } else if (!committed) {
        console.log('We aborted the transaction.');
    } else {
        console.log('Success!');
    }
    console.log("Credit data: ", snapshot.val());
});

Upvotes: 1

Related Questions