(可選)使用 Firebase 本機模擬器套件進行原型設計和測試
在討論您的應用程式如何讀取和寫入即時資料庫之前,我們先介紹一組可用於原型設計和測試即時資料庫功能的工具:Firebase Local Emulator Suite。如果您正在嘗試不同的資料模型、優化安全規則或努力尋找與後端互動的最具成本效益的方式,那麼能夠在本地工作而不部署即時服務可能是一個好主意。
即時資料庫模擬器是本機模擬器套件的一部分,它使您的應用程式能夠與模擬資料庫內容和配置以及可選的模擬專案資源(函數、其他資料庫和安全規則)進行互動。
使用即時資料庫模擬器只需幾個步驟:
- 將一行程式碼新增至應用程式的測試配置以連接到模擬器。
- 從本地專案目錄的根目錄中,運行
firebase emulators:start
。 - 像往常一樣使用即時資料庫平台 SDK 或使用即時資料庫 REST API 從應用程式的原型程式碼進行呼叫。
提供了涉及即時資料庫和雲端功能的詳細演練。您還應該看看本地仿真器套件的介紹。
取得資料庫參考
要從資料庫讀取或寫入數據,您需要一個firebase.database.Reference
實例:
Web modular API
import { getDatabase } from "firebase/database"; const database = getDatabase();
Web namespaced API
var database = firebase.database();
寫入數據
本文檔介紹了檢索資料以及如何排序和過濾 Firebase 資料的基礎知識。
透過將非同步偵聽器附加到firebase.database.Reference
來檢索 Firebase 資料。偵聽器在資料初始狀態時觸發一次,並在資料變更時再次觸發。
基本寫入操作
對於基本寫入操作,您可以使用set()
將資料儲存到指定的引用,替換該路徑上的任何現有資料。例如,社交部落格應用程式可能會使用set()
來新增用戶,如下所示:
Web modular API
import { getDatabase, ref, set } from "firebase/database"; function writeUserData(userId, name, email, imageUrl) { const db = getDatabase(); set(ref(db, 'users/' + userId), { username: name, email: email, profile_picture : imageUrl }); }
Web namespaced API
function writeUserData(userId, name, email, imageUrl) { firebase.database().ref('users/' + userId).set({ username: name, email: email, profile_picture : imageUrl }); }
使用set()
會覆寫指定位置的數據,包括任何子節點。
讀取數據
監聽值事件
若要讀取路徑上的資料並偵聽更改,請使用onValue()
來觀察事件。您可以使用此事件讀取給定路徑中內容的靜態快照,因為它們在事件發生時已存在。此方法在附加偵聽器時觸發一次,每次資料(包括子項目)發生變更時都會觸發一次。向事件回調傳遞包含該位置的所有資料(包括子資料)的快照。如果沒有數據,則當您呼叫exists()
時快照將傳回false
,而當您對其呼叫val()
時快照將傳回null
。
以下範例示範了一個社交部落格應用程式從資料庫中檢索貼文的星級計數:
Web modular API
import { getDatabase, ref, onValue } from "firebase/database"; const db = getDatabase(); const starCountRef = ref(db, 'posts/' + postId + '/starCount'); onValue(starCountRef, (snapshot) => { const data = snapshot.val(); updateStarCount(postElement, data); });
Web namespaced API
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount'); starCountRef.on('value', (snapshot) => { const data = snapshot.val(); updateStarCount(postElement, data); });
偵聽器接收包含事件發生時資料庫中指定位置的資料的snapshot
。您可以使用val()
方法檢索snapshot
中的資料。
讀取一次數據
使用 get() 讀取一次數據
該 SDK 旨在管理與資料庫伺服器的交互,無論您的應用程式是在線還是離線。
通常,您應該使用上述值事件技術來讀取數據,以從後端獲取數據更新的通知。偵聽器技術可減少您的使用量和計費,並經過最佳化,可為您的使用者提供線上和離線時的最佳體驗。
如果您只需要一次數據,則可以使用get()
從資料庫取得資料的快照。如果因任何原因get()
無法傳回伺服器值,用戶端將探測本機儲存緩存,如果仍未找到該值,則傳回錯誤。
不必要地使用get()
會增加頻寬的使用並導致效能損失,這可以透過使用即時偵聽器來防止,如上所示。
Web modular API
import { getDatabase, ref, child, get } from "firebase/database"; const dbRef = ref(getDatabase()); get(child(dbRef, `users/${userId}`)).then((snapshot) => { if (snapshot.exists()) { console.log(snapshot.val()); } else { console.log("No data available"); } }).catch((error) => { console.error(error); });
Web namespaced API
const dbRef = firebase.database().ref(); dbRef.child("users").child(userId).get().then((snapshot) => { if (snapshot.exists()) { console.log(snapshot.val()); } else { console.log("No data available"); } }).catch((error) => { console.error(error); });
用觀察者讀取一次數據
在某些情況下,您可能希望立即傳回本機快取中的值,而不是檢查伺服器上的更新值。在這些情況下,您可以使用once()
立即從本機磁碟快取中取得資料。
這對於只需要載入一次並且預計不會頻繁更改或需要主動偵聽的資料非常有用。例如,前面範例中的部落格應用程式在用戶開始創作新貼文時使用此方法載入用戶的個人資料:
Web modular API
import { getDatabase, ref, onValue } from "firebase/database"; import { getAuth } from "firebase/auth"; const db = getDatabase(); const auth = getAuth(); const userId = auth.currentUser.uid; return onValue(ref(db, '/users/' + userId), (snapshot) => { const username = (snapshot.val() && snapshot.val().username) || 'Anonymous'; // ... }, { onlyOnce: true });
Web namespaced API
var userId = firebase.auth().currentUser.uid; return firebase.database().ref('/users/' + userId).once('value').then((snapshot) => { var username = (snapshot.val() && snapshot.val().username) || 'Anonymous'; // ... });
更新或刪除數據
更新特定字段
若要同時寫入節點的特定子節點而不覆寫其他子節點,請使用update()
方法。
當呼叫update()
時,您可以透過指定鍵的路徑來更新較低層級的子值。如果資料儲存在多個位置以更好地擴展,您可以使用資料扇出更新該資料的所有實例。
例如,社交部落格應用程式可能會建立一個帖子,並同時使用以下程式碼將其更新為最近的活動來源和發文使用者的活動來源:
Web modular API
import { getDatabase, ref, child, push, update } from "firebase/database"; function writeNewPost(uid, username, picture, title, body) { const db = getDatabase(); // A post entry. const postData = { author: username, uid: uid, body: body, title: title, starCount: 0, authorPic: picture }; // Get a key for a new Post. const newPostKey = push(child(ref(db), 'posts')).key; // Write the new post's data simultaneously in the posts list and the user's post list. const updates = {}; updates['/posts/' + newPostKey] = postData; updates['/user-posts/' + uid + '/' + newPostKey] = postData; return update(ref(db), updates); }
Web namespaced API
function writeNewPost(uid, username, picture, title, body) { // A post entry. var postData = { author: username, uid: uid, body: body, title: title, starCount: 0, authorPic: picture }; // Get a key for a new Post. var newPostKey = firebase.database().ref().child('posts').push().key; // Write the new post's data simultaneously in the posts list and the user's post list. var updates = {}; updates['/posts/' + newPostKey] = postData; updates['/user-posts/' + uid + '/' + newPostKey] = postData; return firebase.database().ref().update(updates); }
此範例使用push()
在包含/posts/$postid
處所有使用者的帖子的節點中建立帖子,並同時檢索金鑰。然後,該金鑰可用於在/user-posts/$userid/$postid
處的使用者貼文中建立第二個條目。
使用這些路徑,您可以透過一次呼叫update()
對 JSON 樹中的多個位置執行同步更新,例如本範例如何在兩個位置建立新貼文。以這種方式進行的同時更新是原子的:要么所有更新成功,要么所有更新失敗。
新增完成回調
如果您想知道資料何時提交,可以新增完成回呼。 set()
和update()
都採用一個可選的完成回調,當寫入已提交到資料庫時呼叫該回呼。如果呼叫不成功,則會向回呼傳遞一個錯誤對象,指示失敗的原因發生。
Web modular API
import { getDatabase, ref, set } from "firebase/database"; const db = getDatabase(); set(ref(db, 'users/' + userId), { username: name, email: email, profile_picture : imageUrl }) .then(() => { // Data saved successfully! }) .catch((error) => { // The write failed... });
Web namespaced API
firebase.database().ref('users/' + userId).set({ username: name, email: email, profile_picture : imageUrl }, (error) => { if (error) { // The write failed... } else { // Data saved successfully! } });
刪除數據
刪除資料最簡單的方法是在對該資料位置的參考上呼叫remove()
。
您也可以透過將null
指定為另一個寫入操作(例如set()
或update()
的值來刪除。您可以將此技術與update()
結合使用,以在單一 API 呼叫中刪除多個子項。
收到Promise
若要了解您的資料何時提交至 Firebase 即時資料庫伺服器,您可以使用Promise
。 set()
和update()
都可以傳回一個Promise
,您可以使用它來了解寫入何時提交到資料庫。
分離監聽器
透過呼叫 Firebase 資料庫引用上的off()
方法來刪除回呼。
您可以透過將單一監聽器作為參數傳遞給off()
來刪除它。在不帶參數的位置呼叫off()
會刪除該位置的所有偵聽器。
在父監聽器上呼叫off()
不會自動刪除在其子節點上註冊的監聽器;也必須在任何子偵聽器上呼叫off()
以刪除回呼。
將資料儲存為交易
當處理可能被並發修改損壞的資料(例如增量計數器)時,您可以使用交易操作。您可以為此操作提供更新函數和可選的完成回呼。更新函數將資料的目前狀態作為參數,並傳回您想要寫入的新的所需狀態。如果在成功寫入新值之前另一個用戶端寫入該位置,則會使用新的目前值再次呼叫您的更新函數,並重試寫入。
例如,在範例社交部落格應用程式中,您可以允許用戶對貼文加註星標和取消星標,並追蹤貼文收到的星數,如下所示:
Web modular API
import { getDatabase, ref, runTransaction } from "firebase/database"; function toggleStar(uid) { const db = getDatabase(); const postRef = ref(db, '/posts/foo-bar-123'); runTransaction(postRef, (post) => { if (post) { if (post.stars && post.stars[uid]) { post.starCount--; post.stars[uid] = null; } else { post.starCount++; if (!post.stars) { post.stars = {}; } post.stars[uid] = true; } } return post; }); }
Web namespaced API
function toggleStar(postRef, uid) { postRef.transaction((post) => { if (post) { if (post.stars && post.stars[uid]) { post.starCount--; post.stars[uid] = null; } else { post.starCount++; if (!post.stars) { post.stars = {}; } post.stars[uid] = true; } } return post; }); }
如果多個使用者同時為同一個貼文加註星標或客戶端的資料過時,使用交易可以防止星數計數不正確。如果事務被拒絕,伺服器將目前值傳回給客戶端,用戶端使用更新後的值再次執行事務。如此重複,直到交易被接受或您中止交易。
原子伺服器端增量
在上面的用例中,我們將兩個值寫入資料庫:為貼文加註星標/取消加註星標的使用者的 ID,以及增加的星數。如果我們已經知道用戶正在為帖子加註星標,我們可以使用原子增量操作而不是事務。
Web modular API
function addStar(uid, key) { import { getDatabase, increment, ref, update } from "firebase/database"; const dbRef = ref(getDatabase()); const updates = {}; updates[`posts/${key}/stars/${uid}`] = true; updates[`posts/${key}/starCount`] = increment(1); updates[`user-posts/${key}/stars/${uid}`] = true; updates[`user-posts/${key}/starCount`] = increment(1); update(dbRef, updates); }
Web namespaced API
function addStar(uid, key) { const updates = {}; updates[`posts/${key}/stars/${uid}`] = true; updates[`posts/${key}/starCount`] = firebase.database.ServerValue.increment(1); updates[`user-posts/${key}/stars/${uid}`] = true; updates[`user-posts/${key}/starCount`] = firebase.database.ServerValue.increment(1); firebase.database().ref().update(updates); }
此程式碼不使用事務操作,因此如果存在更新衝突,它不會自動重新運行。但是,由於增量操作直接發生在資料庫伺服器上,因此不會發生衝突。
如果您想要偵測並拒絕特定於應用程式的衝突,例如使用者為他們之前已經加註過星標的貼文加註星標,您應該為該用例編寫自訂安全規則。
離線處理數據
如果客戶端失去網路連接,您的應用程式將繼續正常運作。
連接到 Firebase 資料庫的每個用戶端都會維護自己的任何活動資料的內部版本。寫入資料時,請先寫入此本機版本。然後,Firebase 用戶端會「盡力」將該資料與遠端資料庫伺服器和其他用戶端同步。
因此,在將任何資料寫入伺服器之前,對資料庫的所有寫入都會立即觸發本機事件。這意味著無論網路延遲或連接如何,您的應用程式都保持回應。
重新建立連線後,您的應用程式會收到適當的事件集,以便用戶端與目前伺服器狀態同步,而無需編寫任何自訂程式碼。
我們將在了解有關線上和離線功能的更多資訊中詳細討論離線行為。