使用 Cloud Functions (第 2 代) 擴充與 MongoDB 相容的 Cloud Firestore

使用 Cloud Functions,您可以部署程式碼來處理因與 MongoDB 相容的 Cloud Firestore 資料庫變更而觸發的事件。您不必執行自己的伺服器,就能為應用程式新增伺服器端功能。

Cloud Functions (第 2 代)

Cloud Functions for Firebase (第 2 代) 採用 Cloud RunEventarc,可提供更強大的基礎架構、進一步掌控效能和擴充性,以及加強控管函式執行階段。如要進一步瞭解第 2 代,請參閱「Firebase 專用的 Cloud Functions (第 2 代)」。

與 MongoDB 相容的 Cloud Firestore 函式觸發條件

Cloud Functions for Firebase SDK 會匯出下列與 MongoDB 相容的 Cloud Firestore 事件觸發條件,方便您建立與特定與 MongoDB 相容的 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 包含額外驗證資訊

與 MongoDB 相容的 Cloud Firestore 事件只會在文件變更時觸發。如果更新與 MongoDB 相容的 Cloud Firestore 文件,但資料未變更 (無作業寫入),系統不會產生更新或寫入事件。無法將事件新增至特定欄位。

如果尚未為 Cloud Functions for Firebase 啟用專案,請參閱「開始使用 Cloud Functions for Firebase (第 2 代)」,設定 Cloud Functions for Firebase 專案。

編寫由與 MongoDB 相容的 Cloud Firestore 觸發的函式

定義函式觸發條件

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

Node.js

const {
  onDocumentWritten,
  onDocumentCreated,
  onDocumentUpdated,
  onDocumentDeleted,
  Change,
  FirestoreEvent
} = require('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

const {
  onDocumentWritten,
  Change,
  FirestoreEvent
} = require('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

const {
  onDocumentWritten,
  Change,
  FirestoreEvent
} = require('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 的萬用字元。

系統會從文件路徑擷取萬用字元相符項目,並儲存至 event.params。 即使使用萬用字元,觸發條件一律必須指向文件。

事件觸發條件

在新文件建立時觸發函式

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

Node.js

const {
  onDocumentCreated,
  Change,
  FirestoreEvent
} = require('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

const {
  onDocumentUpdated,
  Change,
  FirestoreEvent
} = require('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

const {
  onDocumentDeleted,
  Change,
  FirestoreEvent
} = require('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 ...

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

如果您不介意觸發的事件類型,可以使用「文件寫入」事件觸發條件,監聽與 MongoDB 相容的 Cloud Firestore 文件中的所有變更。如果使用者建立、更新或刪除,這個範例函式就會觸發:

Node.js

const {
  onDocumentWritten,
  Change,
  FirestoreEvent
} = require('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 中與 MongoDB 相容的資料庫中的特定文件建立關聯。您可以在傳回函式的快照中存取該文件。

文件參照包含 update()set()remove() 等方法,因此您可以修改觸發函式的文件。

Node.js

const {onDocumentUpdated} = require('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 event.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

const {onDocumentWrittenWithAuthContext} = require('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({
      # ...
  })

限制

  • 我們不保證排序。快速變更可能會以非預期的順序觸發函式呼叫。
  • 系統至少會遞送一次事件,但單一事件可能會導致多次函式叫用。請避免依賴「只執行一次」機制,並編寫等冪函式
  • 觸發程序會與單一資料庫建立關聯。您無法建立與多個資料庫相符的觸發條件。
  • 刪除資料庫時,系統不會自動刪除該資料庫的任何觸發程序。觸發程序會停止傳送事件,但會繼續存在,直到您刪除觸發程序為止。