简体   繁体   English

我应该使用 Cloud Functions 还是客户端逻辑来更新 Firebase 中的计数器?

[英]Shall I use Cloud Functions or client logic to update a counter in Firebase?

noob Firebase user here!新手 Firebase 用户在这里!

Initially, I tried to do this as a cloud function and I failed.最初,我尝试以云 function 的形式执行此操作,但失败了。 Now I can do it but I cannot figure out what is the advantage or disadvantage of using one or the other?现在我可以做到了,但我无法弄清楚使用其中一种的优点或缺点是什么? ¯_(ツ)_/¯ ¯_(ツ)_/¯

When should I use cloud functions and when client-side logic?什么时候应该使用云函数,什么时候使用客户端逻辑? I need, please, a mental model to navigate this issue.我需要一个精神上的 model 来解决这个问题。

I ended up doing this to update a simple counter of downloads and it works:我最终这样做是为了更新一个简单的下载计数器并且它有效:


const { firebase, userAuth } = useContext(FirebaseContext);

const countLinkClicks = async (id, userId) => {
        
        const statsRef = firebase.db.collection('publicProfiles').doc('--stats--');
        await statsRef.update({
            totalDownloads: firebase.increment
        })
        
    }

'firebase' and 'increment' are defined in another file: 'firebase' 和 'increment' 在另一个文件中定义:

class Firebase {
  constructor(app) {
    if (!firebaseInstance) {
      app.initializeApp(firebaseConfig);

      this.auth = app.auth();
      this.db = app.firestore();
      this.functions = app.functions();
      this.storage = app.storage();
      this.googleProvider = new app.auth.GoogleAuthProvider()
      this.facebookProvider = new app.auth.FacebookAuthProvider()
      this.increment = new app.firestore.FieldValue.increment(1)
    }
  }

Many thanks非常感谢

Most likely i would go the client route.很可能我会 go 客户端路由。 This way you have all the other advantages of firestore on the client like streaming API and whatnot.这样您就可以在客户端上获得 firestore 的所有其他优势,例如流式传输 API 等等。 Hiding this stuff behind a REST API or something might be ok too, but in the end you will most likely want to use the firestore client anyway for other things.将这些东西隐藏在 REST API 或其他东西后面也可能没问题,但最后你很可能想要使用 firestore 客户端来做其他事情。

So as always, it depends.所以一如既往,这取决于。 Without knowing what you are creating, its a tough question anyway.不知道你在创造什么,无论如何这是一个棘手的问题。

But let me give you an example:但是让我举个例子:

If you are developing a mobile business application and you want to have realtime updates of say, current stock quotes.如果您正在开发移动业务应用程序并且希望实时更新当前股票报价。 You need the client to make this pleasant to code.您需要客户使编码变得愉快。

If you have a game where you only need to update a score and do perhaps only a few more db related things, i would start thinking coding the db updates behind a RESTful service or something.如果你有一个游戏,你只需要更新分数并且可能只做一些与数据库相关的事情,我会开始考虑在 RESTful 服务或其他东西后面编写数据库更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM