Reputation: 573
I'm using Firebase cloud functions in my app to count likes of users. I have node of likes that when user like a video it saves his ID and a boolean parameter (true).
Here example
On the Firebase cloud functions i listen to that node, when new like added it count the likes. as you can see "likes:3".
Cloud function code - update the counter
exports.countlikechange = functions.database.ref('/likes/{postid}/{userUID}').onWrite(event => {
const collectionRef = event.data.ref.parent;
console.log(collectionRef);
const countRef = collectionRef.child('likes');
// Return the promise from countRef.transaction() so our function
// waits for this async event to complete before it exits.
return countRef.transaction(current => {
if (event.data.exists() && !event.data.previous.exists()) {
return (current || 0) + 1;
}
else if (!event.data.exists() && event.data.previous.exists()) {
return (current || 0) - 1;
}
}).then(() => {
console.log('Counter updated.');
});
});
That method listens to the "likes" node and when a child added it trigger that method and update the "likes:.." on each videoID.
What im trying to do is first i want to update the counter in other node
On that node i also want to update the counter.
My problem is that i dont know how to get the reference to that node. On the "HipHop" node, videos are saved, each video saved under his ID.
How can i reference from the cloud functions to that node and update the "likes"??
EDIT Also how can i retrive the data from the node that i'm listening.
for example im listening to the "likes" node, i want to retrive the data that just update in that node.
Upvotes: 2
Views: 1149
Reputation: 1758
You could write something like this:
exports.countlikechange = functions.database.ref('/likes/{postid}/{userUID}').onWrite(event => {
const collectionRef = event.data.ref.parent;
const countRef = collectionRef.child('likes');
const promises = [];
if (event.data.exists() && !event.data.previous.exists()) {
const promisseadd1 = countRef.transaction(current => {
return (current || 0) + 1;
});
const promisseadd2 = admin.database().ref(`/enter/here/new/path/likes`).transaction(current => {
return (current || 0) + 1;
});
return Promise.all([promisseadd1, promisseadd2]);
} else if (!event.data.exists() && event.data.previous.exists()) {
const promissesubs1 = countRef.transaction(current => {
return (current || 0) - 1;
});
const promissesubs2 = admin.database().ref(`/enter/here/new/path/likes`).transaction(current => {
return (current || 0) - 1;
});
return Promise.all([promissesubs1, promissesubs2]);
}
});
Upvotes: 2