Firebase control server for maintaining counters a

2019-01-05 05:48发布

It's a known issue that firebase doesn't have easy way to count items. I'm planning to create an app that relies heavily on counts and other aggregates. I fear creating this app's counters with the rules as suggested here will be incredibly complex and hard to maintain.

So I thought about this pattern:

I will keep a server that will listen to all items entered in the database and this server will update all counters and aggregates. The server will hold the UID of a special admin that only he can update counters.

This way, users will not have to download entire nodes in order to get a count, plus I won't have to deal with issues that arise from maintaining counters by clients.

Does this pattern make sense? Am I missing something?

1条回答
姐就是有狂的资本
2楼-- · 2019-01-05 06:08

Firebase has recently released Cloud Functions. As mentioned on the documentation:

Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code.

With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.

For example, let's say you want to count the number of likes in a post. You should have a structure similar to this one:

{
  "Posts" : {
    "randomKey" : {
      "likes_count":5,
      "likes" : {
      "userX" : true,
      "userY" : true,
      "userZ" : true,
      ...
    }
    }
  }
}

And your JavaScript function would be written like this:

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());
});

This code increases the likes_count variable every time there is a new write on the likes node.

This sample is available on GitHub.

查看更多
登录 后发表回答