在網路上讀取及寫入資料

(選用) 使用 Firebase Local Emulator Suite 設計原型並進行測試

在討論應用程式如何從 Realtime Database 讀取及寫入之前, 以下介紹一組工具,可用來設計原型及測試 Realtime Database 功能:Firebase Local Emulator Suite。如要透過其他資料 最佳化安全性規則,或是盡量找出 以符合成本效益的方式與後端互動 未部署即時服務,也是不錯的點子

Realtime Database 模擬器是 Local Emulator Suite 的一部分, 可讓應用程式與模擬的資料庫內容和設定互動,如 以及選用的模擬專案資源 (函式、其他資料庫 和安全性規則)。

使用 Realtime Database 模擬器只需完成幾個步驟:

  1. 將一行程式碼新增至應用程式的測試設定,即可與模擬器連線。
  2. 從本機專案目錄的根目錄中執行 firebase emulators:start
  3. 使用 Realtime Database 平台從應用程式的原型程式碼發出呼叫 或 Realtime Database REST API 繼續使用 SDK。

請參閱有關 Realtime DatabaseCloud Functions 的詳細說明。建議您也參閱 Local Emulator Suite 簡介

取得資料庫參照

如要從資料庫讀取或寫入資料,您需要使用 firebase.database.Reference:

Web

import { getDatabase } from "firebase/database";

const database = getDatabase();

Web

var database = firebase.database();

寫入資料

本文說明擷取資料的基本概念,以及如何排序及篩選資料 Firebase 資料。

將非同步事件監聽器附加至 firebase.database.Reference。系統會針對 判斷資料的初始狀態,並在資料變更時再次執行。

基本寫入作業

針對基本寫入作業,您可以使用 set() 將資料儲存至指定 取代該路徑中的任何現有資料。例如, 網誌應用程式可能會新增具有 set() 的使用者,如下所示:

Web

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

function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

使用 set() 會覆寫指定位置的資料,包括任何子項 節點。

讀取資料

監聽價值事件

如要在路徑中讀取資料及監聽變更,請使用 onValue() 進行觀察 事件。您可以使用此事件來讀取位於 也就是在事件發生時存在的路徑。這個方法 附加監聽器時就會觸發一次,而每當資料 (包括子項) 變更時,就會觸發一次。事件回呼會傳遞一個快照,其中包含 該位置的所有資料,包括兒童資料。如果沒有資料, 呼叫 exists()null 並對其呼叫 val() 時,快照將傳回 false

下列範例示範社交網誌應用程式擷取 資料庫中貼文的星號數:

Web

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

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

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

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

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

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() 時,您可以透過 指定金鑰的路徑如果資料儲存在多個位置,以便進行擴充 您可以使用 kubectl 指令 資料擴散傳遞

舉例來說,社交網誌應用程式可能會建立文章,然後同時更新 將 物件提交至最近的活動動態消息,並使用 改為執行以下動作:

Web

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

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

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

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 Realtime Database 伺服器, 可以使用 Promiseset()update() 都能傳回 Promise,方便您瞭解 都會提交到資料庫

卸離事件監聽器

呼叫 off() 方法,即可移除回呼 Firebase 資料庫參考資料。

將單一事件監聽器做為參數傳遞至 off() 即可移除。 在沒有引數的位置呼叫 off() 會移除該位置的所有事件監聽器 或 HTTP/HTTPS 位置

對父項事件監聽器呼叫 off() 不會 自動移除在子節點上註冊的監聽器; 也必須在任何子項事件監聽器上呼叫 off() 移除回呼。

將資料儲存為交易

使用可能同時受到並行損毀的資料時 例如漸進式計數器 交易作業。 您可以將更新函式提供給這項作業選用 完成回呼。update 函式會將資料的目前狀態視為 引數並傳回要寫入的新所需狀態如果 在成功使用新值之前,另一個用戶端將資料寫入位置 即會使用新的目前值再次呼叫更新函式,且 並在重試寫入時再次寫入

以社交網誌應用程式為例,您可以讓使用者: 為貼文加上星號、移除星號,並追蹤貼文獲得的星星數量 如下所示:

Web

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

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

使用交易時,如果多個 使用者同時對同一則貼文加上星號,或客戶收集到過時資料。如果 交易遭拒,伺服器會傳回 用戶端目前的值,便會使用 更新的值。此操作會重複直到接受交易或您取消交易為止 交易。

整體伺服器端增量

在上述用途中,我們要將兩個值寫入資料庫: 使用者為貼文加上星號/移除星號,以及逐漸增加的星號數量。如果我們 就可以知道使用者已為貼文加上星號 而不是交易作業

Web

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

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 用戶端會將這些資料與遠端資料庫同步處理 並與其他用戶端共用。

因此,所有寫入資料庫的動作都會立即觸發本機事件, 任何資料都會寫入伺服器也就是說,您的應用程式 回應,無論網路延遲或連線。

連線恢復後,應用程式會收到一組適當的 以便用戶端與目前的伺服器狀態同步, 即可撰寫任何自訂程式碼

我們將在下列單元中進一步說明離線行為: 進一步瞭解線上和離線功能

後續步驟