Cloud Firestore Lite Web SDK

Firestore 是可擴充的資料庫解決方案,適合用於在網頁用戶端之間同步資料。

對許多應用程式來說,Firestore 的代管離線支援功能特別重要,可讓您建構回應式應用程式,不受網路延遲或網際網路連線影響。不過,功能豐富的 SDK 會增加應用程式大小。如果應用程式只需要使用基本的建立、讀取、更新和刪除作業,且不需要代管離線支援,Firebase 可提供什麼功能?

解決方案:Firestore Lite

Firestore Lite 是輕量、獨立且僅限 REST 的 Firestore SDK,支援單一文件擷取、查詢執行和文件更新,大小僅為一般 Web SDK 的一小部分。Firestore Lite 省略了延遲補償、離線快取、查詢恢復和快照監聽器,但對於特定用途,縮減程式庫大小和啟動時間是很好的折衷方案。

匯入 Firestore Lite

Firestore Lite 可透過 npm 取得,是模組化 SDK 的一部分。因此完全模組化,且可進行樹狀搖晃。

系統支援下列匯入樣式。

import { initializeApp } from "firebase/app";
import {
   getFirestore,
   getDoc,
   updateDoc
} from 'firebase/firestore/lite';

Firestore Lite 不支援的 API 功能

為了縮減大小並提高速度,Firestore Lite 移除了標準 Firestore SDK 的下列功能:

  • DocumentSnapshot 事件處理常式。不包含 onSnapshot 方法和 DocumentChange、SnapshotListenerOptions、SnapshotMetadata、SnapshotOptions 和 Unsubscribe 物件。
  • Persistence 輔助程式。不包含 enableIndexedDBPersistence、enableMultiTabIndexedDbPersistence 和 clearIndexedDbPersistence 方法。
  • Firestore 套件。不包含 loadBundle 方法和相關方法,以及 LoadBundleTask 和 LoadBundleTaskProgress 物件。

實作文件擷取、查詢和更新

匯入 Firestore Lite 後,您就能使用所有熟悉的 API 取得及更新呼叫。新增資料和取得資料的用途皆適用。

import {
 getFirestore,
 getDoc,
 updateDoc,
 doc
} from '@firebase/firestore/lite';

const firestore = getFirestore(app);
const docRef = doc(firestore, 'collection/doc');
const docSnap = await getDoc(docRef);
await updateDoc(docRef, "field", 'value');

Firestore Lite 的使用時機

決定何時停用標準 Firestore SDK 的離線持續性和快取功能,可能並不容易。請務必瞭解這些功能,再決定是否要捨棄這些功能,改用負擔較低的 Firestore Lite。一般來說,決定是否使用 Firestore Lite 時,請考量下列因素:

  • 線上狀態:Firestore Lite 適用於不需要即時更新且具備連線能力的應用程式。
  • 大小限制:如要縮減整體 JavaScript 軟體包大小,Firestore Lite 是理想選擇。