在 Cloud Firestore 中建構產品

視建構的應用程式的類型而定,您可能會發現哪些使用者或裝置經常在線上 (又稱為偵測「是否存在」) 會很有用。

舉例來說,如果您建構的是社群網路等應用程式,或部署 IoT 裝置機群,可以利用這項資訊顯示在線上且可以免費進行即時通訊的好友清單,或按「上次上線」排序 IoT 裝置。

Cloud Firestore 本身不會支援在家狀態,但您可以使用其他 Firebase 產品來建構連接系統。

解決方案:Cloud Functions 搭配即時資料庫

如要將 Cloud Firestore 連線至 Firebase 即時資料庫的原生存在功能,請使用 Cloud Functions。

使用即時資料庫回報連線狀態,然後透過 Cloud Functions 將複製的資料複製到 Cloud Firestore。

使用即時資料庫的在家狀態功能

首先,請思考即時資料庫傳統在家狀態系統的運作方式。

網站

// Fetch the current user's ID from Firebase Authentication.
var uid = firebase.auth().currentUser.uid;

// Create a reference to this user's specific status node.
// This is where we will store data about being online/offline.
var userStatusDatabaseRef = firebase.database().ref('/status/' + uid);

// We'll create two constants which we will write to 
// the Realtime database when this device is offline
// or online.
var isOfflineForDatabase = {
    state: 'offline',
    last_changed: firebase.database.ServerValue.TIMESTAMP,
};

var isOnlineForDatabase = {
    state: 'online',
    last_changed: firebase.database.ServerValue.TIMESTAMP,
};

// Create a reference to the special '.info/connected' path in 
// Realtime Database. This path returns `true` when connected
// and `false` when disconnected.
firebase.database().ref('.info/connected').on('value', function(snapshot) {
    // If we're not currently connected, don't do anything.
    if (snapshot.val() == false) {
        return;
    };

    // If we are currently connected, then use the 'onDisconnect()' 
    // method to add a set which will only trigger once this 
    // client has disconnected by closing the app, 
    // losing internet, or any other means.
    userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function() {
        // The promise returned from .onDisconnect().set() will
        // resolve as soon as the server acknowledges the onDisconnect() 
        // request, NOT once we've actually disconnected:
        // https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect

        // We can now safely set ourselves as 'online' knowing that the
        // server will mark us as offline once we lose connection.
        userStatusDatabaseRef.set(isOnlineForDatabase);
    });
});

這個範例是完整的即時資料庫存在系統。可處理多個連線中斷、當機等。

連線至 Cloud Firestore

如要在 Cloud Firestore 中實作類似的解決方案,使用相同的即時資料庫程式碼,請使用 Cloud Functions 來讓即時資料庫和 Cloud Firestore 保持同步。

如果您尚未將即時資料庫新增至專案,並納入上述業務解決方案,請先完成這項操作。

接下來,您將透過下列方法將狀態與 Cloud Firestore 同步:

  1. 在本機端傳送至離線裝置的 Cloud Firestore 快取,讓應用程式知道處於離線狀態。
  2. 在全球各地使用 Cloud 函式,讓存取 Cloud Firestore 的其他裝置都知道這部特定裝置處於離線狀態。

更新 Cloud Firestore 的本機快取

我們來看看完成第一個問題所需的變更,也就是更新 Cloud Firestore 的本機快取。

網站

// ...
var userStatusFirestoreRef = firebase.firestore().doc('/status/' + uid);

// Firestore uses a different server timestamp value, so we'll 
// create two more constants for Firestore state.
var isOfflineForFirestore = {
    state: 'offline',
    last_changed: firebase.firestore.FieldValue.serverTimestamp(),
};

var isOnlineForFirestore = {
    state: 'online',
    last_changed: firebase.firestore.FieldValue.serverTimestamp(),
};

firebase.database().ref('.info/connected').on('value', function(snapshot) {
    if (snapshot.val() == false) {
        // Instead of simply returning, we'll also set Firestore's state
        // to 'offline'. This ensures that our Firestore cache is aware
        // of the switch to 'offline.'
        userStatusFirestoreRef.set(isOfflineForFirestore);
        return;
    };

    userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(function() {
        userStatusDatabaseRef.set(isOnlineForDatabase);

        // We'll also add Firestore set here for when we come online.
        userStatusFirestoreRef.set(isOnlineForFirestore);
    });
});

透過這些變更,我們現在確保 local Cloud Firestore 狀態一律會反映裝置的線上/離線狀態。也就是說,您可以監聽 /status/{uid} 文件,並利用這些資料變更 UI,以反映連線狀態。

網站

userStatusFirestoreRef.onSnapshot(function(doc) {
    var isOnline = doc.data().state == 'online';
    // ... use isOnline
});

全域更新 Cloud Firestore

雖然我們的應用程式可以正確回報線上狀態,但「離線」狀態寫入功能僅適用於本機,在恢復連線後不會同步,因此其他 Cloud Firestore 應用程式也無法提供準確的狀態。為達成此目標,我們會使用監控即時資料庫中 status/{uid} 路徑的 Cloud 函式。當即時資料庫值變更的值會在 Cloud Firestore 同步,因此所有使用者的狀態都正確無誤。

Node.js

firebase.firestore().collection('status')
    .where('state', '==', 'online')
    .onSnapshot(function(snapshot) {
        snapshot.docChanges().forEach(function(change) {
            if (change.type === 'added') {
                var msg = 'User ' + change.doc.id + ' is online.';
                console.log(msg);
                // ...
            }
            if (change.type === 'removed') {
                var msg = 'User ' + change.doc.id + ' is offline.';
                console.log(msg);
                // ...
            }
        });
    });

部署此函式之後,您就能使用 Cloud Firestore 執行的完整運作系統。以下是透過 where() 查詢監控所有上線或離線的使用者。

網站

firebase.firestore().collection('status')
    .where('state', '==', 'online')
    .onSnapshot(function(snapshot) {
        snapshot.docChanges().forEach(function(change) {
            if (change.type === 'added') {
                var msg = 'User ' + change.doc.id + ' is online.';
                console.log(msg);
                // ...
            }
            if (change.type === 'removed') {
                var msg = 'User ' + change.doc.id + ' is offline.';
                console.log(msg);
                // ...
            }
        });
    });

限制

使用即時資料庫增加 Cloud Firestore 應用程式的可用性,不僅可擴充且有效,但有一些限制:

  • 取消彈跳 - 在監聽 Cloud Firestore 中的即時變更時,此解決方案可能會觸發多項變更。如果這些變更觸發的事件數量超出您的預期,請手動撤銷 Cloud Firestore 事件。
  • 連線能力:這個實作項目會測量連至即時資料庫 (而非 Cloud Firestore) 的連線能力。如果每個資料庫的連線狀態不同,本解決方案可能會回報不正確的存在狀態。
  • Android:在 Android 裝置上,即時資料庫會在閒置 60 秒後與後端中斷連線。閒置表示沒有開啟的事件監聽器或待處理的作業。如要讓連線保持開啟,建議您在 .info/connected 以外的路徑中加入價值事件監聽器。例如,您可以在每個工作階段開始時執行 FirebaseDatabase.getInstance().getReference((new Date()).toString()).keepSynced()。詳情請參閱偵測連線狀態的相關說明。