使用 Firestore 套裝組合建構工具擴充功能

Firestore Bundle Builder (firestore-bundle-builder) 擴充功能會部署 HTTP 函式,用於提供 Cloud Firestore 資料套件。您可以在 Firestore 文件中定義套件,擴充功能會透過 HTTP 要求提供靜態二進位檔案資料套件,並使用 Firebase Hosting CDN 或 Cloud Storage 提供各種內建快取機制。如果沒有任何套件或現有套件已過期,這項函式會視需要建構並快取新套件。

如要使用這項擴充功能,請先使用擴充功能的管理資訊主頁,在 Firestore 中建立一或多個套裝組合規格。套件規格可讓您定義具名查詢 (要加入套件的集合查詢和特定文件路徑)。

在套件規格中,您也可以定義要在具名查詢中使用的參數。呼叫 HTTP 函式時,您可以使用網址查詢參數設定這些參數的值。

上述連結提供一些操作說明,方便您在本機執行管理公用程式。設定好網頁應用程式後,請前往 localhost:3000,使用 UI 建立規格:

範例

建構及提供套裝組合

安裝擴充功能並建立套件規格後,您就可以呼叫擴充功能提供的 HTTP 端點,開始建構及放送套件。

視套件規格而定,要求的套件可能會從用戶端快取、Firebase Hosting 快取或 Cloud Storage 檔案傳回。所有快取過期後,新的服務要求會觸發 Firestore 查詢,以視需要建構套件。

您可以設定指向服務函式的 Firebase 代管網站,並使用重寫規則,充分運用 Firebase 代管 CDN 的功能。CDN 會在許多不同的伺服器上複製套件,讓使用者自動從最近的伺服器載入套件。建議您採用這種做法。

如要在 Firebase 託管中設定這項功能,請建立或編輯 firebase.json 檔案,加入下列內容並部署網站

{
  "hosting": {
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "/bundles/*",
        "function": "ext-firestore-bundle-builder-serve"
      }
    ]
  }
}

部署完成後,您可以使用網站網址,從 CDN 存取套件。例如 https://your-site-url.com/bundles/:bundleId

如果您不想使用 Firebase 託管,也可以將擴充功能設為在 Cloud Storage 中快取資料。在這種情況下,您會直接呼叫已部署的 HTTP 函式來產生套件。

用戶端整合

接著,您可以使用 Cloud Firestore SDK 的 loadBundle API 消耗套件。首先,您需要下載套件,然後提供給 SDK。例如:

import { loadBundle } from "firebase/firestore";

// Download the bundle from the Firebase Hosting CDN:
const bundle = await fetch("/bundles/:bundleId");

// If not using a CDN, download the bundle directly:
// const bundle = await fetch('https://<location>-<project-id>.cloudfunctions.net/ext-firestore-bundle-builder-serve/:bundleId');

await loadBundle(bundle);

載入後,您可以使用套件中的資料:

如果您在定義套件時指定了文件路徑陣列,即可透過套件在用戶端取得文件資料:

import { getFirestore, doc, getDocFromCache } from "firebase/firestore";
// Bundle Document IDs: ['users/92x1NgSWYKUC4AG4s2nHGMR2ikZ2']

const ref = doc(getFirestore(), "users/92x1NgSWYKUC4AG4s2nHGMR2ikZ2");
const snapshot = await getDocFromCache(ref);

如果您指定了查詢,可以使用 namedQuery API 從套件執行查詢:

import { getFirestore, namedQuery } from "firebase/firestore";
const query = await namedQuery(getFirestore(), "queryId");
const snapshot = await getDocsFromCache(query);

查詢 ID 定義為每個 queries 屬性定義的鍵 (請參閱下文)。