Cloud Firestore Lite Web SDK

Firestore 是理想的可擴充資料庫解決方案,可讓網路用戶端的資料保持同步。

對許多應用程式而言,Firestore 的代管離線支援尤其重要,可讓您建構無論網路延遲或網際網路連線都能運作的回應式應用程式。但功能豐富的 SDK 需要耗費大量資源。如果應用程式只需要使用基本的建立、讀取、更新及刪除作業,而且不需使用代管離線支援,Firebase 可以提供什麼協助?

解決方案:Firestore Lite

Firestore Lite 是輕量級的獨立 REST 專屬 Firestore SDK,可支援一般 Web SDK 大小的部分功能,例如擷取單一文件、執行查詢及更新文件。Firestore Lite 會略過延遲補償、離線快取、查詢恢復和快照事件監聽器,但在特定用途上,減少程式庫大小和啟動時間可以大幅取捨。

匯入 Firestore Lite

透過 npm 取得 Firestore Lite 做為模組 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 非常適合。