使用 Cloud Functions,您可以部署程式碼來處理因 Cloud Firestore 資料庫變更而觸發的事件。這樣一來,您就能輕鬆將伺服器端功能加入應用程式,不必自行執行伺服器。
Cloud Functions (第 2 代)
Cloud Functions for Firebase (第 2 代) 採用 Cloud Run 和 Eventarc,提供更強大的基礎架構、進階效能和擴充性控制功能,以及更完善的函式執行階段控制功能。如要進一步瞭解第 2 代,請參閱「Firebase 專用的 Cloud Functions (第 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 Functions (第 1 代) 的先決條件:Firestore 原生模式中現有的「(預設)」資料庫。不支援 Cloud Firestore 具名資料庫或 Datastore 模式。在這種情況下,請使用 Cloud Functions (第 2 代) 設定事件。
- 我們不保證排序。快速變更可能會以非預期的順序觸發函式呼叫。
- 系統至少會傳送一次事件,但單一事件可能會導致多次函式叫用。請避免依附於「只執行一次」機制,並編寫等冪函式。
- Cloud Firestore (Datastore 模式) 需要 Cloud Functions (第 2 代)。Cloud Functions (第 1 代) 不支援 Datastore 模式。
- 觸發條件會與單一資料庫建立關聯。您無法建立與多個資料庫相符的觸發程序。
- 刪除資料庫時,系統不會自動刪除該資料庫的任何觸發程序。觸發條件會停止傳送事件,但會繼續存在,直到您刪除觸發條件為止。
- 如果相符事件超過要求大小上限,事件可能無法傳送至 Cloud Functions (第 1 代)。
- 如果事件因要求大小而未傳送,系統會記錄在平台記錄中, 並計入專案的記錄檔用量。
- 您可以在記錄檔探索器中找到這些記錄,訊息為「Event cannot deliver to Cloud function due to size exceeding the limit for 1st gen...」(事件無法傳送至 Cloud 函式,因為大小超出第 1 代的限制...),嚴重程度為
error
。您可以在「functionName
」欄位下方找到函式名稱。如果receiveTimestamp
欄位仍在一小時內,您可以讀取時間戳記前後的快照,推斷實際活動內容。 - 如要避免這種情況,可以採取下列做法:
- 遷移及升級至 Cloud Functions (第 2 代)
- 縮小文件
- 刪除有問題的 Cloud Functions
- 您可以使用排除條件關閉記錄功能,但請注意,違規事件仍不會傳送。