了解 2023 年 Google I/O 大会上介绍的 Firebase 亮点。了解详情

Cloud Firestore Lite Web SDK

Firestore 是一個很好的可擴展數據庫解決方案,可以在 Web 客戶端之間保持數據同步。

對於許多應用程序,Firestore 的託管離線支持尤為重要,它讓您構建響應式應用程序,無論網絡延遲或互聯網連接如何都能正常工作。但功能豐富的 SDK 需要付出一定的規模成本。 Firebase 為只需要使用基本創建、讀取、更新和刪除操作而不需要託管離線支持的應用程序提供什麼?

解決方案:Firestore Lite

Firestore Lite 是一款輕量級、獨立的 REST-only Firestore SDK,支持單個文檔提取、查詢執行和文檔更新,大小僅為常規 Web SDK 的一小部分。 Firestore Lite 省略了延遲補償、離線緩存、查詢恢復和快照偵聽器,但對於特定用例,庫大小和啟動時間的減少是一個很好的權衡。

導入 Firestore Lite

Firestore Lite 可作為模塊化 SDK的一部分通過 npm 獲得。因此,它是完全模塊化和可搖樹的。

支持以下導入樣式。

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 是一個不錯的選擇。