สร้างการแสดงข้อมูลใน Cloud Firestore

คุณอาจเห็นว่าการตรวจหานั้นมีประโยชน์ ทั้งนี้ขึ้นอยู่กับประเภทแอปที่กําลังสร้าง ผู้ใช้หรืออุปกรณ์ใดที่ออนไลน์อยู่ หรือเรียกอีกอย่างว่า กำลังตรวจหา "การปรากฏ"

เช่น หากคุณกำลังสร้างแอปอย่างโซเชียลเน็ตเวิร์กหรือติดตั้งใช้งาน กลุ่มอุปกรณ์ IoT คุณสามารถใช้ข้อมูลนี้เพื่อแสดง เพื่อนที่ออนไลน์และแชทได้ฟรี หรือจัดเรียงอุปกรณ์ IoT ของคุณตาม "เห็นครั้งสุดท้าย"

Cloud Firestore ไม่ได้รองรับการตรวจหาบุคคลโดยค่าเริ่มต้น แต่คุณสามารถ ใช้ประโยชน์จากผลิตภัณฑ์อื่นๆ ของ Firebase เพื่อสร้างระบบการตรวจหาบุคคลในบ้าน

โซลูชัน: Cloud Functions ที่มี Realtime Database

วิธีเชื่อมต่อ Cloud Firestore กับโฆษณาเนทีฟของ Firebase Realtime Database การตรวจหาบุคคลในบ้าน ให้ใช้ Cloud Functions

ใช้ Realtime Database เพื่อรายงานสถานะการเชื่อมต่อ จากนั้นใช้ Cloud Functions เพื่อ มิเรอร์ข้อมูลดังกล่าวไปยัง Cloud Firestore

การใช้การปรากฏตัวใน Realtime Database

ก่อนอื่นให้พิจารณาวิธีการทำงานของระบบการตรวจหาบุคคลในบ้านแบบดั้งเดิมใน Realtime Database

เว็บ

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

ตัวอย่างนี้เป็นระบบการตรวจหาบุคคลใน Realtime Database ที่สมบูรณ์ จัดการ การยกเลิกการเชื่อมต่อ การขัดข้อง และอื่นๆ หลายครั้ง

กำลังเชื่อมต่อกับ Cloud Firestore

หากต้องการใช้โซลูชันที่คล้ายกันใน Cloud Firestore ให้ใช้ โค้ด Realtime Database จากนั้นใช้ฟังก์ชัน Cloud Functions เพื่อเก็บ Realtime Database และ Cloud Firestore ซิงค์อยู่

เพิ่มฐานข้อมูลเรียลไทม์ลงในโปรเจ็กต์หากยังไม่ได้เพิ่ม และระบุโซลูชันการแสดงตัวตนข้างต้น

จากนั้นคุณจะซิงค์สถานะการแสดงข้อมูลกับ Cloud Firestore ได้ วิธีการต่อไปนี้

  1. ในเครื่อง ไปยังแคช Cloud Firestore ของอุปกรณ์ออฟไลน์เพื่อให้แอป รู้ว่าออฟไลน์อยู่
  2. ทั่วโลก โดยใช้ฟังก์ชันระบบคลาวด์เพื่อให้อุปกรณ์อื่นๆ ทั้งหมดที่เข้าถึง 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);
    });
});

ปัจจุบันการเปลี่ยนแปลงเหล่านี้ทำให้เรามั่นใจว่าสถานะ Cloud Firestore ในเครื่อง แสดงสถานะออนไลน์/ออฟไลน์ของอุปกรณ์ ซึ่งหมายความว่าคุณสามารถฟัง /status/{uid} เอกสารและใช้ข้อมูลเพื่อเปลี่ยน UI เพื่อแสดงการเชื่อมต่อ สถานะ

เว็บ

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

กำลังอัปเดต Cloud Firestore ทั่วโลก

แม้ว่าแอปพลิเคชันของเราจะรายงานสถานะการออนไลน์ให้ตัวเองทราบอย่างถูกต้อง แต่สถานะนี้ จะยังไม่ถูกต้องในแอป Cloud Firestore อื่นๆ เนื่องจากเรา "ออฟไลน์" การเขียนสถานะเป็นแบบภายในเท่านั้นและจะไม่ถูกซิงค์เมื่อกลับมาเชื่อมต่ออีกครั้ง ต่อรอง เราจะใช้ Cloud Function ที่ดูเส้นทาง status/{uid} แบบเรียลไทม์ ฐานข้อมูล เมื่อค่า Realtime Database เปลี่ยนแปลง ค่าจะซิงค์กับ 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);
                // ...
            }
        });
    });

ข้อจำกัด

การใช้ Realtime Database เพื่อเพิ่มการแสดงข้อมูลในแอป Cloud Firestore สามารถปรับขนาดได้และมีประสิทธิภาพ แต่มีข้อจำกัดบางประการดังนี้

  • การดีเบานซ์ - เมื่อฟังการเปลี่ยนแปลงแบบเรียลไทม์ใน Cloud Firestore โซลูชันนี้น่าจะทริกเกอร์ การเปลี่ยนแปลง หากการเปลี่ยนแปลงเหล่านี้ทริกเกอร์เหตุการณ์มากกว่าที่คุณต้องการ ให้ทำด้วยตนเอง ดีเบานซ์เหตุการณ์ Cloud Firestore
  • การเชื่อมต่อ - การติดตั้งใช้งานนี้วัดการเชื่อมต่อกับแบบเรียลไทม์ ฐานข้อมูล ไม่ใช่ Cloud Firestore หากการเชื่อมต่อ แต่ละฐานข้อมูลไม่เหมือนกัน โซลูชันนี้อาจรายงาน สถานะบุคคลไม่ถูกต้อง
  • Android - ใน Android ฐานข้อมูลเรียลไทม์จะยกเลิกการเชื่อมต่อกับ หลังไม่มีการใช้งานเป็นเวลา 60 วินาที "ไม่มีการใช้งาน" จะทำให้ไม่มี Listener แบบเปิด หรือการดำเนินการที่รอดำเนินการอยู่ เราขอแนะนำให้คุณเพิ่มเพื่อเปิดการเชื่อมต่อ Listener เหตุการณ์ที่มีค่าในเส้นทางที่ไม่ใช่ .info/connected ตัวอย่างเช่น คุณ สามารถทำFirebaseDatabase.getInstance().getReference((new Date()).toString()).keepSynced() ที่จุดเริ่มต้นของแต่ละเซสชัน สำหรับข้อมูลเพิ่มเติม โปรดดู กำลังตรวจหาสถานะการเชื่อมต่อ