透過 Cloud Functions (第 2 代) 擴充 Cloud Firestore

您可以透過 Cloud Functions 部署程式碼來處理觸發的事件 藉此因應 Cloud Firestore 資料庫的變更這樣您就能輕鬆新增伺服器端 整合到您的應用程式中,不必使用自己的伺服器。

Cloud Functions (第 2 代)

採用 Cloud RunEventarc、 Cloud Functions for Firebase (第 2 代) 提供更多強大功能 基礎架構、效能和擴充性進階控管機制 函式執行階段的控制。如要進一步瞭解第 2 代,請參閱 Cloud Functions for Firebase (第 2 代)。瞭解詳情 請參閱第 1 代的相關知識 使用 Cloud Functions 擴充 Cloud Firestore

Cloud Firestore 函式觸發條件

Cloud Functions for Firebase SDK 會匯出下列 Cloud Firestore 事件觸發條件,可讓您建立與特定 Cloud Firestore 繫結的處理常式 事件:

Node.js

事件類型 觸發條件
onDocumentCreated 在第一次寫入文件時觸發。
onDocumentUpdated 在文件已經存在且已變更任何值時觸發。
onDocumentDeleted 在文件刪除時觸發。
onDocumentWritten 在觸發 onDocumentCreatedonDocumentUpdatedonDocumentDeleted 時觸發。
onDocumentCreatedWithAuthContext 包含其他驗證資訊的onDocumentCreated
onDocumentWrittenWithAuthContext 包含其他驗證資訊的onDocumentWritten
onDocumentDeletedWithAuthContext 包含其他驗證資訊的onDocumentDeleted
onDocumentUpdatedWithAuthContext 包含其他驗證資訊的onDocumentUpdated

Python (預先發布版)

事件類型 觸發條件
on_document_created 在第一次寫入文件時觸發。
on_document_updated 在文件已經存在且已變更任何值時觸發。
on_document_deleted 在文件刪除時觸發。
on_document_written 在觸發 on_document_createdon_document_updatedon_document_deleted 時觸發。
on_document_created_with_auth_context 包含其他驗證資訊的on_document_created
on_document_updated_with_auth_context 包含其他驗證資訊的on_document_updated
on_document_deleted_with_auth_context 包含其他驗證資訊的on_document_deleted
on_document_written_with_auth_context 包含其他驗證資訊的on_document_written

僅觸發 Cloud Firestore 事件 文件變更時Cloud Firestore 文件更新,其中含有資料 未變更 (免人工操作寫入) 不會產生更新或寫入事件。是 無法將事件新增至特定欄位。

如果您尚未啟用 Cloud Functions for Firebase 專案,請閱讀 開始使用 Cloud Functions for Firebase (第 2 代) 來設定及設定 Cloud Functions for Firebase 專案。

編寫 Cloud Firestore 觸發函式

定義函式觸發條件

如要定義 Cloud Firestore 觸發條件,請指定文件路徑和事件類型:

Node.js

import {
  onDocumentWritten,
  onDocumentCreated,
  onDocumentUpdated,
  onDocumentDeleted,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("my-collection/{docId}", (event) => {
   /* ... */ 
});

Python (預先發布版)

from firebase_functions.firestore_fn import (
  on_document_created,
  on_document_deleted,
  on_document_updated,
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_created(document="users/{userId}")
def myfunction(event: Event[DocumentSnapshot]) -> None:

文件路徑可以參照特定文件萬用字元模式

指定單一文件

如果您想在特定文件發生「任何」變更時觸發事件,則 可以使用下列函式

Node.js

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("users/marie", (event) => {
  // Your code here
});

Python (預先發布版)

from firebase_functions.firestore_fn import (
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_written(document="users/marie")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:

使用萬用字元指定一組文件

如果您想將觸發條件附加至一組文件,例如 特定集合,然後使用 {wildcard} 取代 文件 ID:

Node.js

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("users/{userId}", (event) => {
  // If we set `/users/marie` to {name: "Marie"} then
  // event.params.userId == "marie"
  // ... and ...
  // event.data.after.data() == {name: "Marie"}
});

Python (預先發布版)

from firebase_functions.firestore_fn import (
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_written(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # If we set `/users/marie` to {name: "Marie"} then
  event.params["userId"] == "marie"  # True
  # ... and ...
  event.data.after.to_dict() == {"name": "Marie"}  # True

在這個範例中,當 users 中任何文件的任何欄位有所變更時, 名為 userId 的萬用字元。

如果 users 中的文件含有子集合,且其中一個欄位設有欄位 子集合文件有所變更,因此「不會」觸發 userId 萬用字元。

萬用字元比對結果會從文件路徑擷取,並儲存至 event.params。 您可以定義任意數量的萬用字元來取代明確集合 或文件 ID,例如

Node.js

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.myfunction = onDocumentWritten("users/{userId}/{messageCollectionId}/{messageId}", (event) => {
    // If we set `/users/marie/incoming_messages/134` to {body: "Hello"} then
    // event.params.userId == "marie";
    // event.params.messageCollectionId == "incoming_messages";
    // event.params.messageId == "134";
    // ... and ...
    // event.data.after.data() == {body: "Hello"}
});

Python (預先發布版)

from firebase_functions.firestore_fn import (
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_written(document="users/{userId}/{messageCollectionId}/{messageId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # If we set `/users/marie/incoming_messages/134` to {body: "Hello"} then
  event.params["userId"] == "marie"  # True
  event.params["messageCollectionId"] == "incoming_messages"  # True
  event.params["messageId"] == "134"  # True
  # ... and ...
  event.data.after.to_dict() == {"body": "Hello"}

即使使用萬用字元,觸發條件「一律」必須指向特定文件。 舉例來說,由於 {messageCollectionId}users/{userId}/{messageCollectionId} 無效 是一個集合不過,users/{userId}/{messageCollectionId}/{messageId} 有效,因為 {messageId} 一律會指向文件。

事件觸發條件

建立新文件時觸發函式

每當在集合中建立新文件時,您可以觸發函式。 以下函式範例會在每次新增使用者設定檔時觸發:

Node.js

import {
  onDocumentCreated,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.createuser = onDocumentCreated("users/{userId}", (event) => {
    // Get an object representing the document
    // e.g. {'name': 'Marie', 'age': 66}
    const snapshot = event.data;
    if (!snapshot) {
        console.log("No data associated with the event");
        return;
    }
    const data = snapshot.data();

    // access a particular field as you would any JS property
    const name = data.name;

    // perform more operations ...
});

如需其他驗證資訊,請使用 onDocumentCreatedWithAuthContext

Python (預先發布版)

from firebase_functions.firestore_fn import (
  on_document_created,
  Event,
  DocumentSnapshot,
)

@on_document_created(document="users/{userId}")
def myfunction(event: Event[DocumentSnapshot]) -> None:
  # Get a dictionary representing the document
  # e.g. {'name': 'Marie', 'age': 66}
  new_value = event.data.to_dict()

  # Access a particular field as you would any dictionary
  name = new_value["name"]

  # Perform more operations ...

在文件更新時觸發函式

也可以觸發在文件更新時觸發的函式。 以下範例函式會在使用者變更設定檔時觸發:

Node.js

import {
  onDocumentUpdated,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.updateuser = onDocumentUpdated("users/{userId}", (event) => {
    // Get an object representing the document
    // e.g. {'name': 'Marie', 'age': 66}
    const newValue = event.data.after.data();

    // access a particular field as you would any JS property
    const name = newValue.name;

    // perform more operations ...
});

如需其他驗證資訊,請使用 onDocumentUpdatedWithAuthContext

Python (預先發布版)

from firebase_functions.firestore_fn import (
  on_document_updated,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_updated(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # Get a dictionary representing the document
  # e.g. {'name': 'Marie', 'age': 66}
  new_value = event.data.after.to_dict()

  # Access a particular field as you would any dictionary
  name = new_value["name"]

  # Perform more operations ...

在文件刪除時觸發函式

您也可以在刪除文件時觸發函式。本例 函式:

Node.js

import {
  onDocumentDeleted,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.deleteuser = onDocumentDeleted("users/{userId}", (event) => {
    // Get an object representing the document
    // e.g. {'name': 'Marie', 'age': 66}
    const snap =  event.data;
    const data =  snap.data();

    // perform more operations ...
});

如需其他驗證資訊,請使用 onDocumentDeletedWithAuthContext

Python (預先發布版)

from firebase_functions.firestore_fn import (
  on_document_deleted,
  Event,
  DocumentSnapshot,
)

@on_document_deleted(document="users/{userId}")
def myfunction(event: Event[DocumentSnapshot|None]) -> None:
  # Perform more operations ...

針對文件的所有變更觸發函式

如果您不在意所觸發的事件類型,可以監聽 活動 觸發。以下範例函式會在建立、更新或刪除使用者時觸發:

Node.js

import {
  onDocumentWritten,
  Change,
  FirestoreEvent
} from "firebase-functions/v2/firestore";

exports.modifyuser = onDocumentWritten("users/{userId}", (event) => {
    // Get an object with the current document values.
    // If the document does not exist, it was deleted
    const document =  event.data.after.data();

    // Get an object with the previous document values
    const previousValues =  event.data.before.data();

    // perform more operations ...
});

如需其他驗證資訊,請使用 onDocumentWrittenWithAuthContext

Python (預先發布版)

from firebase_functions.firestore_fn import (
  on_document_written,
  Event,
  Change,
  DocumentSnapshot,
)

@on_document_written(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot | None]]) -> None:
  # Get an object with the current document values.
  # If the document does not exist, it was deleted.
  document = (event.data.after.to_dict()
              if event.data.after is not None else None)

  # Get an object with the previous document values.
  # If the document does not exist, it was newly created.
  previous_values = (event.data.before.to_dict()
                     if event.data.before is not None else None)

  # Perform more operations ...

讀取及寫入資料

觸發函式時,系統會提供函式相關資料快照 活動。您可以使用這張快照讀取或寫入 觸發了該事件,或者使用 Firebase Admin SDK 存取其他部分 備用資源數量

事件資料

讀取資料

觸發函式時,您可能需要從 或先取得資料,再進行更新。如要取得先前的資料,請使用 event.data.before,包含更新前的文件快照。 同樣地,event.data.after 包含文件快照狀態, 更新。

Node.js

exports.updateuser2 = onDocumentUpdated("users/{userId}", (event) => {
    // Get an object with the current document values.
    // If the document does not exist, it was deleted
    const newValues =  event.data.after.data();

    // Get an object with the previous document values
    const previousValues =  event.data.before.data();
});

Python (預先發布版)

@on_document_updated(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # Get an object with the current document values.
  new_value = event.data.after.to_dict()

  # Get an object with the previous document values.
  prev_value = event.data.before.to_dict()

您可以像存取其他物件一樣存取屬性。或者,您也可以 可以使用 get 函式存取特定欄位:

Node.js

// Fetch data using standard accessors
const age = event.data.after.data().age;
const name = event.data.after.data()['name'];

// Fetch data using built in accessor
const experience = event.data.after.data.get('experience');

Python (預先發布版)

# Get the value of a single document field.
age = event.data.after.get("age")

# Convert the document to a dictionary.
age = event.data.after.to_dict()["age"]

寫入資料

每個函式叫用都會與 Cloud Firestore 資料庫您可以在 傳回給函式的快照

文件參考資料包含 update()set()remove() 等方法 方便您修改觸發函式的文件。

Node.js

import { onDocumentUpdated } from "firebase-functions/v2/firestore";

exports.countnamechanges = onDocumentUpdated('users/{userId}', (event) => {
  // Retrieve the current and previous value
  const data = event.data.after.data();
  const previousData = event.data.before.data();

  // We'll only update if the name has changed.
  // This is crucial to prevent infinite loops.
  if (data.name == previousData.name) {
    return null;
  }

  // Retrieve the current count of name changes
  let count = data.name_change_count;
  if (!count) {
    count = 0;
  }

  // Then return a promise of a set operation to update the count
  return data.after.ref.set({
    name_change_count: count + 1
  }, {merge: true});

});

Python (預先發布版)

@on_document_updated(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:
  # Get the current and previous document values.
  new_value = event.data.after
  prev_value = event.data.before

  # We'll only update if the name has changed.
  # This is crucial to prevent infinite loops.
  if new_value.get("name") == prev_value.get("name"):
      return

  # Retrieve the current count of name changes
  count = new_value.to_dict().get("name_change_count", 0)

  # Update the count
  new_value.reference.update({"name_change_count": count + 1})

存取使用者驗證資訊

如果您使用下列任一事件類型,就能存取 觸發事件的主體的使用者驗證資訊。 除了基本事件中傳回的資訊外,這項資訊也包含在內。

Node.js

  • onDocumentCreatedWithAuthContext
  • onDocumentWrittenWithAuthContext
  • onDocumentDeletedWithAuthContext
  • onDocumentUpdatedWithAuthContext

Python (預先發布版)

  • on_document_created_with_auth_context
  • on_document_updated_with_auth_context
  • on_document_deleted_with_auth_context
  • on_document_written_with_auth_context

如需瞭解驗證情境中可用的資料,請參閱 驗證情境: 以下範例說明如何擷取驗證資訊:

Node.js

import { onDocumentWrittenWithAuthContext } from "firebase-functions/v2/firestore"

exports.syncUser = onDocumentWrittenWithAuthContext("users/{userId}", (event) => {
    const snapshot = event.data.after;
    if (!snapshot) {
        console.log("No data associated with the event");
        return;
    }
    const data = snapshot.data();

    // retrieve auth context from event
    const { authType, authId } = event;

    let verified = false;
    if (authType === "system") {
      // system-generated users are automatically verified
      verified = true;
    } else if (authType === "unknown" || authType === "unauthenticated") {
      // admin users from a specific domain are verified
      if (authId.endsWith("@example.com")) {
        verified = true;
      }
    }

    return data.after.ref.set({
        created_by: authId,
        verified,
    }, {merge: true}); 
}); 

Python (預先發布版)

@on_document_updated_with_auth_context(document="users/{userId}")
def myfunction(event: Event[Change[DocumentSnapshot]]) -> None:

  # Get the current and previous document values.
  new_value = event.data.after
  prev_value = event.data.before

  # Get the auth context from the event
  user_auth_type = event.auth_type
  user_auth_id = event.auth_id

觸發事件以外的資料

Cloud Functions 會在受信任的環境中執行。這些 可以在專案中使用服務帳戶 寫入使用 Firebase Admin SDK

Node.js

const { initializeApp } = require('firebase-admin/app');
const { getFirestore, Timestamp, FieldValue } = require('firebase-admin/firestore');

initializeApp();
const db = getFirestore();

exports.writetofirestore = onDocumentWritten("some/doc", (event) => {
    db.doc('some/otherdoc').set({ ... });
  });

  exports.writetofirestore = onDocumentWritten('users/{userId}', (event) => {
    db.doc('some/otherdoc').set({
      // Update otherdoc
    });
  });

Python (預先發布版)

from firebase_admin import firestore, initialize_app
import google.cloud.firestore

initialize_app()

@on_document_written(document="some/doc")
def myfunction(event: Event[Change[DocumentSnapshot | None]]) -> None:
  firestore_client: google.cloud.firestore.Client = firestore.client()
  firestore_client.document("another/doc").set({
      # ...
  })

限制

請注意下列 Cloud Functions 的 Cloud Firestore 觸發條件限制:

  • Cloud Functions (第 1 代) 必須符合現有的「(預設)」條件Vertex AI 原生模式沒有 支援 Cloud Firestore 具名資料庫或 Datastore 模式。請使用 Cloud Functions (第 2 代) 在這類情況下設定事件。
  • 我們不保證排序。快速變更可觸發下列時間中的函式叫用: 以免發生非預期的訂單
  • 事件至少會傳送一次,但單一事件可能會導致 多個函式叫用。避免取決於 僅須執行一次的機制 冪等函式
  • Cloud Firestore (Datastore 模式) 需要 Cloud Functions (第 2 代)Cloud Functions (第 1 代) 不會 支援 Datastore 模式
  • 觸發條件與單一資料庫相關聯。無法建立與多個資料庫相符的觸發條件。
  • 刪除資料庫不會自動刪除該資料庫的任何觸發條件。 觸發條件會停止傳送事件,但直到您刪除觸發條件為止。
  • 如果相符的事件超過請求大小上限, 事件可能不會傳送至 Cloud Functions (第 1 代)。
    • 因要求大小而未傳送的事件會記錄在平台記錄檔中 並會計入專案的記錄檔用量。
    • 您可以在記錄檔探索工具中找到這些記錄,並查看「事件無法傳送至 超出第 1 代限制的 Cloud 函式...」/error 嚴重性。您可以在 functionName 欄位下方找到函式名稱。如果 receiveTimestamp 欄位至今仍在一小時內,因此您可以推斷 閱讀相關文件,瞭解實際活動內容 是在時間戳記前後建立的快照
    • 如要避免這種展示頻率,可以採取下列做法:
      • 遷移並升級至 Cloud Functions (第 2 代)
      • 將文件縮小
      • 刪除有問題的 Cloud Functions
    • 您可以使用排除功能來關閉記錄功能 但請注意,違規活動將不會送達。