Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion child-count/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ This template shows how to keep track of the number of elements in a Firebase Da

See file [functions/index.js](functions/index.js) for the code.

This is done by simply updating a `likes_count` attribute on the parent of the list node which is tracked.
This is done by updating a `likes_count` property on the parent of the list node which is tracked.

This counting is done in two cases:

1. When a like is added or deleted, the `likes_count` is incremented or decremented.
2. When the `likes_count` is deleted, all likes are recounted.

The dependencies are listed in [functions/package.json](functions/package.json).

Expand Down
27 changes: 24 additions & 3 deletions child-count/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,28 @@ const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// Keeps track of the length of the 'likes' child list in a separate attribute.
exports.countlikes = functions.database.ref('/posts/{postid}/likes').onWrite(event => {
return event.data.ref.parent.child('likes_count').set(event.data.numChildren());
// Keeps track of the length of the 'likes' child list in a separate property.
exports.countlikechange = functions.database.ref("/posts/{postid}/likes/{likeid}").onWrite((event) => {
var collectionRef = event.data.ref.parent;
var countRef = collectionRef.parent.child('likes_count');

return countRef.transaction(function(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;
}
});
});

// If the number of likes gets deleted, recount the number of likes
exports.recountlikes = functions.database.ref("/posts/{postid}/likes_count").onWrite((event) => {
if (!event.data.exists()) {
var counterRef = event.data.ref;
var collectionRef = counterRef.parent.child('likes');
return collectionRef.once('value', function(messagesData) {
return counterRef.set(messagesData.numChildren());
});
}
});