Cloud Firestore Lite Web SDK

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

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

解決方案:Firestore Lite

Firestore Lite 是輕量級的獨立 Firestore SDK,僅支援 REST,但能以一小部分的 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 方法和 DocumentChangeSnapshotListenerOptionsSnapshotMetadataSnapshotOptionsUnsubscribe 物件。
  • 持續性輔助程式。不包括 enableIndexedDBPersistenceenableMultiTabIndexedDbPersistenceclearIndexedDbPersistence 方法。
  • Firestore 組合包。不包含 loadBundle 方法和相關方法,以及 LoadBundleTaskLoadBundleTaskProgress 物件。

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

匯入 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 是絕佳選擇。