Firebase transaction in nodeJs


Firebase transaction in nodeJs



What I try to achieve is simply increase a value in the database with a transaction. This is working for me as intended, but I always get following error in my firebase console:


Function returned undefined, expected Promise or value



My current call is as following:


exports.reportCounter = functions.database.ref('/user/{userId}/reports/{initiatorId}').onWrite((change,context) => {
const userId = context.params.userId;

return userRef.child(userId).child("numReports").transaction(function(numReports) {
return change.after.exists()?((numReports || 0) + 1):(numReports - 1);
})
});



I also tried returning the promise directly:


return userRef.child(userId).child("numToIncrement").transaction(function(numToIncrement) {
return ((numToIncrement || 0) + 1);
});



In both cases, the code is doing what it is supposed to do, but I still receive said error.
enter image description here





You should be able to return the promise directly. Please edit your question to show the entire code sample when you tried that.
– Doug Stevenson
Jun 30 at 19:50





I edited my post. I actually get another error when I try returning the promise directly, but this somehow seems to vary.
– Thomas
Jun 30 at 20:01





What do you mean "seems to vary"?
– Doug Stevenson
Jun 30 at 20:04





I sometimes get "Function returned undefined, expected Promise or value", and sometimes I get "Error serializing return value: TypeError: Converting circular structure to JSON"
– Thomas
Jun 30 at 20:05




1 Answer
1



This is how you should implement the transaction, this way the function always returns a promise:


exports.reportCounter = functions.database.ref('/user/{userId}/reports/{initiatorId}').onWrite((change, context) => {
const userId = context.params.userId;
let increment;
if (change.after.exists() && !change.before.exists()) {
increment = 1;
} else if (!change.after.exists() && change.before.exists()) {
increment = -1;
}
return userRef.child(userId).child("numReports").transaction(function(numReports) {
return (numReports || 0) + increment;
})
});





I still get "Error serializing return value: TypeError: Converting circular structure to JSON". I guess it has something to do with the fact, that transactions are being called more often than once in Firebase.
– Thomas
Jun 30 at 21:22






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API