在 Firebase 中处理用户的在线和离线状态

Luk*_*kas 5 javascript firebase firebase-realtime-database google-cloud-functions

我想在我的网络应用程序中处理在线和离线状态。以便用户可以看到谁在线、谁不在线。

我发现这个很棒的教程解释得很好,但我被困住了。

https://blog.campvanilla.com/firebase-firestore-guide-how-to-user-presence-online-offline-basics-66dc27f67802

我认为 存在问题cloud-functions,因为我在那里遇到了错误。

此外,该教程是从 2017 年 12 月 15 日开始的,我知道该教程cloud-functions已更新,但我不知道如何更新代码。

链接到文档:https ://firebase.google.com/docs/functions/beta-v1-diff

有人可以看一下教程并可以帮助我吗?

云功能:

 const functions = require('firebase-functions');
 const Firestore = require('@google-cloud/firestore');
 const firestore = new Firestore();

 exports.onUserStatusChanged = functions.database
  .ref('/status/{userId}') // Reference to the Firebase RealTime database key
  .onUpdate((event, context) => {

    const usersRef = firestore.collection('/users'); // Create a reference to 
    the Firestore Collection

    return event.before.ref.once('value')
      .then(statusSnapshot => snapShot.val()) // Get latest value from  the Firebase Realtime database
      .then(status => {
        // check if the value is 'offline'
        if (status === 'offline') {
          // Set the Firestore's document's online value to false
          usersRef
            .doc(event.params.userId)
            .set({
              online: false
            }, {
              merge: true
            });
        }
        return
      })
  });
Run Code Online (Sandbox Code Playgroud)

Joe*_*ler 7

官方 Firestore 文档中有一个更新的教程(在 Cloud Firestore 中构建存在),解释了如何设置 Firestore、实时数据库和 Cloud Functions。


Dan*_*ial 6

我只是要发布功能齐全的代码来帮助像我一样坚持使用它的其他人。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const firestore = functions.firestore;

exports.onUserStatusChange = functions.database
    .ref('/status/{userId}')
    .onUpdate((event, context) => {

        var db = admin.firestore();
        var fieldValue = require("firebase-admin").firestore.FieldValue;

        const usersRef = db.collection("users");
        var snapShot = event.after;

        return event.after.ref.once('value')
            .then(statusSnap => snapShot.val())
            .then(status => {
                if (status === 'offline'){
                    usersRef
                        .doc(context.params.userId)
                        .set({
                            online: false
                        }, {merge: true});

                }
                return null;
            })
});
Run Code Online (Sandbox Code Playgroud)