Simon k
Simon k

Reputation: 413

Firebase functions - adding new value to the oldvalue

I'm creating an android app that logs how long a person spends on certain things. I want to add the time spent to the total time spend, so I know how long a user has spent on an exercise type I want to do it in a function, since I think it's easier than transactions.

exports.addExerciseTime = functions.database.ref('users/{userid}/stats/exerciseTime/{type}').onWrite( event =>{
        console.log("Exercise time updates...");
        var newdata = event.data.val();
        var oldData = event.data.previous.val();
        return event.data.ref.update(oldData+ newdata);
    });

Now, I know that this function will loop until firebase shuts it down.

But how would I do this? Is there an easier way to do this?

Upvotes: 1

Views: 242

Answers (2)

J. Doe
J. Doe

Reputation: 13113

Like you are saying, onWrite will capture every writing event. My solution would be replacing onWrite with onCreate, however let the user write to another path because Firebase will keep triggering the function. Besides that, your approach this is not the best solution since the updates can conflict. The use of transactions is better. That would look like this:

exports.addExerciseTime = functions.database.ref('users/{userid}/stats/exerciseTime/{type}').onCreate( event =>{
        console.log("Exercise time updates...");
        var newdata = event.data.val();
        const pathToValue = //create the path here to exercisetime
        return pathToValue.transaction(function(exercisetime) {
        return (exercisetime || 0) + newdata;
       });
    });

*Notice the onCreate event instead of onWrite. Again: You will need to write it to a other path.

Upvotes: 1

Ben Yitzhaki
Ben Yitzhaki

Reputation: 1426

you have an easy option of adding a flag indicating that you updated the data. next time you will get into the function, just start by checking if the flag exists in if so, exit the function. the con of this one is that you will run the function at least n+1

another option, according to their latest post, you know have a "onUpdate" and "onCreate" triggers as well. you might be able to use them smartly to optimize this even more (for example: only on first creation do XYZ, so it won't run on each update).

https://firebase.googleblog.com/2017/07/cloud-functions-realtime-database.html

Upvotes: 1

Related Questions