透過 Cloud Functions,您可以部署程式碼來處理因 Cloud Firestore 資料庫變更而觸發的事件。這可讓您輕鬆在應用程式中加入伺服器端功能,而不必執行自己的伺服器。
Cloud Functions (第 2 代)
Cloud Functions for Firebase (第 2 代) 採用 Cloud Run 和 Eventarc,提供更強大的基礎架構、進一步控管效能和擴充性,還可讓您進一步控管函式執行階段。如要進一步瞭解第 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 |
在觸發 onDocumentCreated 、onDocumentUpdated 或 onDocumentDeleted 時觸發。 |
onDocumentCreatedWithAuthContext |
包含其他驗證資訊的onDocumentCreated |
onDocumentWrittenWithAuthContext |
包含其他驗證資訊的onDocumentWritten |
onDocumentDeletedWithAuthContext |
包含其他驗證資訊的onDocumentDeleted |
onDocumentUpdatedWithAuthContext |
包含其他驗證資訊的onDocumentUpdated |
Python (預先發布版)
事件類型 | 觸發條件 |
---|---|
on_document_created |
在第一次寫入文件時觸發。 |
on_document_updated |
在文件已經存在且已變更任何值時觸發。 |
on_document_deleted |
在刪除文件時觸發。 |
on_document_written |
在觸發 on_document_created 、on_document_updated 或 on_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"}
即使您使用萬用字元,觸發條件也「一律」必須指向文件。舉例來說,users/{userId}/{messageCollectionId}
無效,因為 {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 ...
對文件的所有變更觸發函式
如果您不在乎要觸發的事件類型,可以使用「已寫入的文件」事件觸發條件監聽 Cloud Firestore 文件中的所有變更。以下範例函式會在使用者建立、更新或刪除時觸發:
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 Firestore (Datastore 模式) 需要 Cloud Functions (第 2 代)。Cloud Functions (第 1 代) 不支援 Datastore 模式。
- Cloud Functions (第 1 代) 僅適用於「(預設)」資料庫,且不支援 Cloud Firestore 已命名資料庫。請使用 Cloud Functions (第 2 代) 為已命名的資料庫設定事件。
- 觸發條件與單一資料庫相關聯。您無法建立與多個資料庫相符的觸發條件。
- 刪除資料庫不會自動刪除該資料庫的任何觸發條件。觸發條件會停止傳送事件,但在您刪除觸發條件前會持續存在。
- 如果相符的事件超過要求大小上限,該事件可能無法傳送至 Cloud Functions (第 1 代)。
- 因要求大小而未傳送的事件會記錄在平台記錄中,並計入專案的記錄檔用量。
- 您可以在記錄檔探索工具中找到這些記錄,並顯示以下訊息:「由於大小超過第 1 代 (第 1 代) 的限制,因此事件無法傳送至 Cloud Functions」(第 1 代嚴重性為
error
)。您可以在functionName
欄位下方找到函式名稱。如果receiveTimestamp
欄位目前仍在一小時後,則可透過讀取時間戳記前後的快照,讀取相關的文件,藉此推斷實際的事件內容。 - 如要避免這類頻率,你可以採取下列做法:
- 遷移並升級至 Cloud Functions (第 2 代)
- 縮小文件
- 刪除相關的 Cloud 函式
- 您可以使用排除來關閉記錄本身,但請注意,系統不會傳送違規事件。