Browse Source

Split the child counting into two functions:

1. tracks add/remove of child nodes and increments/decrements the counter
2. one function is triggered when the counter is deleted and it recounts the child nodes

The delta counter in #1 is more efficient than counting all children every time, since it only needs
access to the delta. The recounter function in #2 is equally inefficient as before, but is needed
a lot less.
katowulf-pr-tpl
Frank van Puffelen 8 years ago
parent
commit
5b31834071
  1. 7
      child-count/README.md
  2. 27
      child-count/functions/index.js

7
child-count/README.md

@ -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. 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). The dependencies are listed in [functions/package.json](functions/package.json).

27
child-count/functions/index.js

@ -19,7 +19,28 @@ const functions = require('firebase-functions');
const admin = require('firebase-admin'); const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase); admin.initializeApp(functions.config().firebase);
// Keeps track of the length of the 'likes' child list in a separate attribute. // Keeps track of the length of the 'likes' child list in a separate property.
exports.countlikes = functions.database.ref('/posts/{postid}/likes').onWrite(event => { exports.countlikechange = functions.database.ref("/posts/{postid}/likes/{likeid}").onWrite((event) => {
return event.data.ref.parent.child('likes_count').set(event.data.numChildren()); 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());
});
}
});
Loading…
Cancel
Save