I have a leaderboard in firebase database. I have set up an .indexOn rule for score and userName. I add records to it, get the top ten, these go fast and are easily achieved on client side.
But retrieving the current user's rank can get really slow on client side, since I have to get the full list of children of the leaderboard node and count the records until I find the users record... This leaderboard could get up to 100k records in it. Not to mention that this comes with huge network traffic.
I would like to use firebase Functions to order and rank the records when inserting a record, so I can keep network traffic as low as possible.
My structure is like this:
"leaderboard": {
"user_id_xxxx":
{
"uid": "user_id_xxxx",
"userName" : "someone",
"score": 99999
"rank": 1
},
"user_id_xxxy":
{
"uid": "user_id_xxxy",
"userName" : "otherone",
"score": 99998
"rank": 2
}
}
So I have come up with a code snippet, but I don't know how to order it:
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var dbRef = functions.database.ref('/leaderboard');
exports.dbRefOnWriteEvent = .onWrite(event => {
const parentRef = event.data.ref.parent();
return parentRef.once('value').then(snapshot => {
var i = 1;
const updates = {};
snapshot.forEach(function(child) {
child.rank = i;
i++;
});
return parentRef.update(updates);
});
});
I appreciate any suggestions and help, I'm still learning node.js and Firebase Functions
via McDermott
No comments:
Post a Comment