Wednesday, 10 May 2017

Incremential operation with Firebase Functions

I am trying to create a function for my database using Firebase Functions. The purpose of the function is to listen to write events on the attend table and based on the object written to identify the event and increment the usersAttending on the event object.

This is my function so far.

//listens to write on attendObjects (when a user is attending an event), and increments attending users for event 
exports.listenAttendingEvents = functions.database.ref('/attendObject/{pushId}').onWrite(event => {

//get attendObj -> parsed JSON by javascript interpreter
const attentObj = event.data.val();
console.log('attentObj is loaded as', attentObj); //contains eventId + user info
const evnetId = attentObj['attendObjectEventId'];
console.log('eventId is loaded as', evnetId);
const pathToAttendees = '/events' + '/' + evnetId;

console.log('path to pathToAttendees = ' + pathToAttendees);

// Attach an asynchronous callback to read the data at our posts reference
 admin.database().ref(pathToAttendees).on("value", function(snapshot) {
  console.log(snapshot.val());
  const eventObj = snapshot.val();
    var nrAttending = eventObj['usersAttending'];
        console.log('nr attending exists', "", nrAttending || 1 - 1);
         nrAttending = Number(snapshot.val());
         return admin.database().ref(pathToAttendees + '/usersAttending').transaction(function (nrAttending) {
             return (nrAttending || 0) + 1;
        }); 
    });
}, function (errorObject) {
   console.log("The read failed: " + errorObject.code);
   return errorObject
});

The problems as it seems is that the event object doesn't get retrieved. The function seems to finish before that with the status ok



via John

No comments:

Post a Comment