建立擴充功能時,您可以使用 Cloud Functions 編寫其邏輯,就像編寫僅在您自己的專案中使用的函數一樣。您在extension.yaml
檔案中聲明您的函數,當使用者安裝您的擴充功能時,這些函數將部署到他們的專案中。
有關使用Cloud Functions 的一般信息,請參閱 Cloud Functions文件。
第一代與第二代雲端功能
Firebase 支援第一代和第二代 Cloud Functions 。但是,Firebase Extensions 目前對可與某些觸發器類型一起使用哪一代雲端函數有一些限制。因此,許多擴充都包含第一代和第二代功能的混合。
下面註明了每種觸發器類型的函數產生支援。
特別注意事項
某些函數定義要求您指定也在
extension.yaml
檔案中指定的資訊。例如,Cloud Firestore 有一個document()
方法,用於指定要監視的文件模式,並且其在extension.yaml
中的對應聲明具有指定相同內容的resource
欄位。在這些情況下,將使用
extension.yaml
檔案中指定的配置,並忽略函數定義中指定的配置。為了方便記錄,通常的做法是在函數定義中指定配置的值。本頁上的範例遵循此模式。
Cloud Functions 第一代 SDK 具有
functions.config()
方法和functions:config:set
CLI 指令,您可以使用它們來處理第一代函數中的參數化值。此技術在 Cloud Functions 中已棄用,並且在擴充功能中根本不起作用。相反,請使用functions.params
模組(建議)或process.env
。
使用 TypeScript
大多數用於開發自己的擴充功能的文件都描述了使用 JavaScript for Cloud Functions for Firebase 的工作流程。但是,您可以使用 TypeScript 編寫函數。
事實上,所有官方 Firebase 擴充都是用 TypeScript 編寫的。您可以查看這些擴展,以了解在擴展中使用 TypeScript 的一些最佳實踐。
如果您確實使用 TypeScript 編寫擴充功能的函數,則必須在安裝擴充功能之前執行以下操作:
將擴充的函數原始碼編譯為 JavaScript。
firebase ext:dev:init
指令可讓您選擇 TypeScript 來編寫函數。該命令為您提供了完整的、可安裝的擴充功能以及可以使用npm run build
運行的建置腳本。在
package.json
檔案中,確保將main
欄位指向產生的 JavaScript。如果您要從本機來源安裝或上傳擴展,請先編譯 TypeScript 檔案。
支援的功能觸發器
HTTP 觸發器
HTTP 觸發的函數部署到公用https
端點,並在存取該端點時執行。
有關編寫 HTTP 觸發函數的信息,請參閱 Cloud Functions 文件中的透過 HTTP 請求呼叫函數。
函數定義(僅限第一代)
import { https } from "firebase-functions/v1";
export const yourFunctionName = https.onRequest(async (req, resp) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
runtime: nodejs16
httpsTrigger: {}
- name: anotherFunction
type: ...
可呼叫函數
可呼叫函數與 HTTP 觸發的函數類似,但它們實作了一個協議,使您可以輕鬆地從客戶端程式碼呼叫它們。
有關使用可呼叫函數的信息,請參閱 Cloud Functions 文件中的從應用程式呼叫函數。
函數定義(僅限第一代)
import { https } from "firebase-functions/v1";
export const yourFunctionName = https.onCall(async (data, context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
runtime: nodejs16
httpsTrigger: {}
- name: anotherFunction
type: ...
預定功能觸發器
計劃函數根據可自訂的計劃重複運行。
有關編寫計劃函數的信息,請參閱 Cloud Functions 文件中的計劃函數。
函數定義(僅限第一代)
import { pubsub } from "firebase-functions/v1";
export const yourFunctionName = pubsub.schedule("every 6 hours").onRun((context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
scheduleTrigger:
schedule: 'every 5 minutes'
- name: anotherFunction
type: ...
以下是scheduleTrigger
的可用子欄位:
場地 | 描述 |
---|---|
schedule (必需的) | 您希望函數運行的頻率。 此欄位可以接受使用任一語法的字串(需要用單引號括起來):
|
timeZone (選修的) | 計劃將運行的時區。
|
如果您希望使用者在安裝擴充功能時能夠配置計劃,請在您的extension.yaml
檔案中新增一個新參數,並在函數的resource
聲明中引用該參數:
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
scheduleTrigger:
schedule: ${SCHEDULE_FREQUENCY}
- name: anotherFunction
type: ...
params:
- param: SCHEDULE_FREQUENCY
label: Schedule
description: How often do you want to run yourFunctionName()?
type: string
default: 'every 5 minutes' # Specifying a default is optional.
required: true
任務隊列觸發器
任務佇列函數會在擴充功能的生命週期事件發生時觸發,或在使用 Admin SDK 的TaskQueue.enqueue()
方法手動新增至擴充功能的任務佇列時觸發。
有關編寫處理生命週期事件的函數的信息,請參閱處理擴展的生命週期事件。
有關編寫任務佇列函數的信息,請參閱 Cloud Functions 文件中的將函數與雲端任務一起排隊。
函數定義(僅限第一代)
import { tasks } from "firebase-functions/v1";
export const yourFunctionName = tasks.taskQueue().onDispatch(async (data, context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: myTaskFunction
type: firebaseextensions.v1beta.function
description: >-
Perform a task when triggered by a lifecycle event
properties:
taskQueueTrigger: {}
將taskQueueTrigger
屬性設定為{}
或調整任務佇列的速率限制和重試行為的選項對應(請參閱調整任務佇列)。
如果您想在擴充功能的生命週期事件上觸發函數,請新增包含函數名稱和可選處理訊息的lifecycleEvents
記錄,該訊息將在處理開始時顯示在 Firebase 控制台中。
lifecycleEvents:
onInstall:
function: myTaskFunction
processingMessage: Resizing your existing images
onUpdate:
function: myOtherTaskFunction
processingMessage: Setting up your extension
onConfigure:
function: myOtherTaskFunction
processingMessage: Setting up your extension
分析
當記錄指定的 Analytics 事件時,Analytics 觸發的函數就會運作。
有關編寫Analytics 觸發函數的信息,請參閱 Cloud Functions 文件中的 Google Analytics 觸發器。
函數定義(僅限第一代)
import { analytics } from "firebase-functions/v1";
export const yourFunctionName = analytics.event("event_name").onLog((event, context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: providers/google.firebase.analytics/eventTypes/event.log
resource: projects/${PROJECT_ID}/events/ga_event
- name: anotherFunction
type: ...
如果您希望使用者能夠設定在安裝擴充功能時偵聽的 Analytics 事件,請在您的extension.yaml
檔案中新增一個新參數,並在函數的resource
宣告中引用該參數:
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: providers/google.firebase.analytics/eventTypes/event.log
resource: projects/${PROJECT_ID}/events/${EVENT_NAME}
- name: anotherFunction
type: ...
params:
- param: EVENT_NAME
label: Analytics event
description: What event do you want to respond to?
type: string
default: ga_event # Specifying a default is optional.
required: true
驗證
認證觸發函數在建立或刪除使用者時運行。
有關編寫身份驗證觸發函數的信息,請參閱 Cloud Functions 文件中的Firebase 身份驗證觸發器。
函數定義(僅限第一代)
import { auth } from "firebase-functions/v1";
export const yourFunctionName = auth.user().onCreate((user, context) => {
// ...
});
export const yourFunctionName2 = auth.user().onDelete((user, context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: providers/firebase.auth/eventTypes/user.create
resource: projects/${PROJECT_ID}
- name: anotherFunction
type: ...
下表顯示如何指定每個受支援的身份驗證事件類型:
Cloud Functions 事件觸發器 | eventType | 描述 |
---|---|---|
onCreate() | providers/firebase.auth/eventTypes/user.create | 新用戶已創建 |
onDelete() | providers/firebase.auth/eventTypes/user.delete | 用戶已刪除 |
雲端Firestore
Cloud Firestore 觸發的函數會在建立、更新或刪除文件時執行。
有關編寫 Firestore 觸發函數的信息,請參閱 Cloud Functions 文件中的Cloud Firestore 觸發器。
函數定義(僅限第一代)
import { firestore } from "firebase-functions/v1";
export const yourFunctionName = firestore.document("collection/{doc_id}")
.onCreate((snapshot, context) => {
// ...
});
export const yourFunctionName2 = firestore.document("collection/{doc_id}")
.onUpdate((change, context) => {
// ...
});
export const yourFunctionName3 = firestore.document("collection/{doc_id}")
.onDelete((snapshot, context) => {
// ...
});
export const yourFunctionName4 = firestore.document("collection/{doc_id}")
.onWrite((change, context) => {
// onWrite triggers on creation, update, and deletion.
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: providers/cloud.firestore/eventTypes/document.write
resource: projects/${PROJECT_ID}/databases/(default)/documents/collection/{documentID}
- name: anotherFunction
type: ...
下表顯示如何指定每個支援的 Cloud Firestore 事件類型:
Cloud Functions 事件觸發器 | eventType | 描述 |
---|---|---|
onCreate() | providers/cloud.firestore/eventTypes/document.create | 新文件已建立 |
onDelete() | providers/cloud.firestore/eventTypes/document.delete | 文件已刪除 |
onUpdate() | providers/cloud.firestore/eventTypes/document.update | 文件已更新 |
onWrite() | providers/cloud.firestore/eventTypes/document.write | 建立、刪除或更新的文檔 |
如果您希望使用者在安裝擴充功能時能夠配置文件路徑,請在您的extension.yaml
檔案中新增一個參數,並在函數的resource
宣告中引用該參數:
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: providers/cloud.firestore/eventTypes/document.write
resource: projects/${PROJECT_ID}/databases/(default)/documents/${YOUR_DOCUMENT_PATH}
- name: anotherFunction
type: ...
params:
- param: YOUR_DOCUMENT_PATH
label: Cloud Firestore path
description: Where do you want to watch for changes?
type: string
default: path/to/{documentID} # Specifying a default is optional.
required: true
發布/訂閱
當訊息發佈到特定主題時,Pub/Sub 觸發函數就會運作。
有關編寫Pub/Sub 觸發函數的信息,請參閱 Cloud Functions 文件中的 Pub/Sub 觸發器。
函數定義(僅限第一代)
import { pubsub } from "firebase-functions/v1";
export const yourFunctionName = pubsub.topic("topic_name").onPublish((message, context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: google.pubsub.topic.publish
resource: projects/${PROJECT_ID}/topics/topic-name
- name: anotherFunction
type: ...
如果您希望使用者在安裝擴充功能時能夠配置 Pub/Sub 主題,請在您的extension.yaml
檔案中新增一個新參數,並在函數的resource
宣告中引用該參數:
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: google.pubsub.topic.publish
resource: projects/${PROJECT_ID}/topics/${PUBSUB_TOPIC}
- name: anotherFunction
type: ...
params:
- param: PUBSUB_TOPIC
label: Pub/Sub topic
description: Which Pub/Sub topic do you want to watch for messages?
type: string
default: topic-name # Specifying a default is optional.
required: true
即時資料庫
當建立、更新或刪除與指定模式相符的路徑時,即時資料庫觸發的函數就會運作。
有關編寫 RTDB 觸發函數的信息,請參閱 Cloud Functions 文件中的即時資料庫觸發器。
函數定義(僅限第一代)
import { database } from "firebase-functions/v1";
export const yourFunctionName = database.ref("path/to/{item}")
.onCreate((snapshot, context) => {
// ...
});
export const yourFunctionName2 = database.ref("path/to/{item}")
.onUpdate((change, context) => {
// ...
});
export const yourFunctionName3 = database.ref("path/to/{item}")
.onDelete((snapshot, context) => {
// ...
});
export const yourFunctionName4 = database.ref("path/to/{item}")
.onWrite((change, context) => {
// onWrite triggers on creation, update, and deletion.
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: providers/google.firebase.database/eventTypes/ref.create
# DATABASE_INSTANCE (project's default instance) is an auto-populated
# parameter value. You can also specify an instance.
resource: projects/_/instances/${DATABASE_INSTANCE}/refs/path/to/{itemId}
- name: anotherFunction
type: ...
下表顯示如何指定每個支援的 Cloud Firestore 事件類型:
Cloud Functions 事件觸發器 | eventType | 描述 |
---|---|---|
onCreate() | providers/google.firebase.database/eventTypes/ref.create | 創建的數據 |
onDelete() | providers/google.firebase.database/eventTypes/ref.delete | 數據已刪除 |
onUpdate() | providers/google.firebase.database/eventTypes/ref.update | 數據已更新 |
onWrite() | providers/google.firebase.database/eventTypes/ref.write | 建立、刪除或更新的數據 |
如果您希望使用者在安裝擴充功能時能夠配置要觀看的路徑,請在您的extension.yaml
檔案中新增一個參數,並在函數的resource
宣告中引用該參數:
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: providers/google.firebase.database/eventTypes/ref.create
# DATABASE_INSTANCE (project's default instance) is an auto-populated
# parameter value. You can also specify an instance.
resource: projects/_/instances/${DATABASE_INSTANCE}/refs/${DB_PATH}
- name: anotherFunction
type: ...
params:
- param: DB_PATH
label: Realtime Database path
description: Where do you want to watch for changes?
type: string
default: path/to/{itemId} # Specifying a default is optional.
required: true
遠端配置
當專案的參數模板更新時,遠端配置觸發的函數將運行。
有關編寫遠端配置觸發函數的信息,請參閱 Cloud Functions 文件中的遠端配置觸發器。
函數定義(僅限第一代)
import { remoteConfig } from "firebase-functions/v1";
export const yourFunctionName = remoteConfig.onUpdate((version, context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: google.firebase.remoteconfig.update
resource: projects/${PROJECT_ID}
- name: anotherFunction
type: ...
雲端儲存
Cloud Storage 觸發的函數會在建立、歸檔或刪除物件或其元資料發生變更時執行。
有關編寫儲存觸發函數的信息,請參閱 Cloud Functions 文件中的雲端儲存觸發器。
函數定義(僅限第一代)
import { storage } from "firebase-functions/v1";
export const yourFunctionName = storage.object().onFinalize((object, context) => {
// ...
});
export const yourFunctionName2 = storage.object().onMetadataUpdate((object, context) => {
// ...
});
export const yourFunctionName3 = storage.object().onArchive((object, context) => {
// ...
});
export const yourFunctionName4 = storage.object().onDelete((object, context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: google.storage.object.finalize
# STORAGE_BUCKET (project's default bucket) is an auto-populated
# parameter. You can also specify a bucket.
resource: projects/_/buckets/${STORAGE_BUCKET}
- name: anotherFunction
type: ...
下表顯示如何指定每個受支援的 Cloud Storage 事件類型:
Cloud Functions 事件觸發器 | eventType | 描述 |
---|---|---|
onFinalize() | google.storage.object.finalize | 物件已建立 |
onMetadataUpdate() | google.storage.object.metadataUpdate | 對像元資料已更新 |
onArchive() | google.storage.object.archive | 物件已存檔 |
onDelete() | google.storage.object.delete | 物件已刪除 |
如果您希望使用者在安裝擴充功能時能夠配置儲存桶,請在您的extension.yaml
檔案中新增一個參數,並在函數的resource
宣告中引用該參數:
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: google.storage.object.finalize
resource: projects/_/buckets/${YOUR_BUCKET}
- name: anotherFunction
type: ...
params:
- param: YOUR_BUCKET
label: Cloud Storage bucket
description: Which bucket do you want to watch for changes?
type: selectResource
resourceType: storage.googleapis.com/Bucket
default: ${STORAGE_BUCKET} # Specifying a default is optional.
required: true
測試實驗室
當測試矩陣完成其測試時,測試實驗室觸發的函數就會運行。
有關編寫測試實驗室觸發函數的信息,請參閱 Cloud Functions 文件中的Firebase 測試實驗室觸發器。
函數定義(僅限第一代)
import { testLab } from "firebase-functions/v1";
export const yourFunctionName = testLab.testMatrix().onComplete((matrix, context) => {
// ...
});
資源聲明(擴展名.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: google.testing.testMatrix.complete
resource: projects/${PROJECT_ID}/testMatrices/{matrixId}
- name: anotherFunction
type: ...
Crashlytics 警報觸發器
當 Crashlytics 發布警報時,Crashlytics 觸發的函數就會運行。
有關編寫警報觸發函數的信息,請參閱 Cloud Functions 文件中的Firebase 警報觸發器。
函數定義(僅限第二代)
import {
onNewFatalIssuePublished,
onNewNonfatalIssuePublished,
onNewAnrIssuePublished,
onRegressionAlertPublished,
onVelocityAlertPublished,
onStabilityDigestPublished,
} from "firebase-functions/v2/alerts/crashlytics";
export const yourFunctionName = onNewFatalIssuePublished((event) => {
// ...
});
export const yourFunctionName2 = onNewNonfatalIssuePublished((event) => {
// ...
});
export const yourFunctionName3 = onNewAnrIssuePublished((event) => {
// ...
});
export const yourFunctionName4 = onRegressionAlertPublished((event) => {
// ...
});
export const yourFunctionName5 = onVelocityAlertPublished((event) => {
// ...
});
export const yourFunctionName6 = onStabilityDigestPublished((event) => {
// ...
});
資源聲明(擴展名.yaml)
apis:
- apiName: eventarc.googleapis.com
reason: Powers all events and triggers
- apiName: run.googleapis.com
reason: Powers 2nd-gen functions
resources:
- name: yourfunctionname
type: firebaseextensions.v1beta.v2function
properties:
buildConfig:
runtime: nodejs16
serviceConfig:
availableMemory: 512M
eventTrigger:
eventType: google.firebase.firebasealerts.alerts.v1.published
triggerRegion: global
eventFilters:
- attribute: alerttype
value: crashlytics.newFatalIssue
- name: anotherFunction
type: ...
您可以使用下列值作為alerttype
-
crashlytics.newFatalIssue
-
crashlytics.newNonfatalIssue
-
crashlytics.regression
-
crashlytics.stabilityDigest
-
crashlytics.velocity
-
crashlytics.newAnrIssue
效能監控警報觸發器
當效能監控發布警報時,效能監控觸發的功能就會運作。
有關編寫警報觸發函數的信息,請參閱 Cloud Functions 文件中的Firebase 警報觸發器。
函數定義(僅限第二代)
import { onThresholdAlertPublished } from "firebase-functions/v2/alerts/performance";
export const yourFunctionName = onThresholdAlertPublished((event) => {
// ...
});
資源聲明(擴展名.yaml)
apis:
- apiName: eventarc.googleapis.com
reason: Powers all events and triggers
- apiName: run.googleapis.com
reason: Powers 2nd-gen functions
resources:
- name: yourfunctionname
type: firebaseextensions.v1beta.v2function
properties:
buildConfig:
runtime: nodejs16
serviceConfig:
availableMemory: 512M
eventTrigger:
eventType: google.firebase.firebasealerts.alerts.v1.published
triggerRegion: global
eventFilters:
- attribute: alerttype
value: performance.threshold
- name: anotherFunction
type: ...
應用程式分發警報觸發器
當 App Distribution 發布警報時,App Distribution 觸發的函數就會運作。
有關編寫警報觸發函數的信息,請參閱 Cloud Functions 文件中的Firebase 警報觸發器。
函數定義(僅限第二代)
import {
onNewTesterIosDevicePublished,
onInAppFeedbackPublished
} from "firebase-functions/v2/alerts/appDistribution";
export const yourFunctionName = onNewTesterIosDevicePublished((event) => {
// ...
});
export const yourFunctionName2 = onInAppFeedbackPublished((event) => {
// ...
});
資源聲明(擴展名.yaml)
apis:
- apiName: eventarc.googleapis.com
reason: Powers all events and triggers
- apiName: run.googleapis.com
reason: Powers 2nd-gen functions
resources:
- name: yourfunctionname
type: firebaseextensions.v1beta.v2function
properties:
buildConfig:
runtime: nodejs16
serviceConfig:
availableMemory: 512M
eventTrigger:
eventType: google.firebase.firebasealerts.alerts.v1.published
triggerRegion: global
eventFilters:
- attribute: alerttype
value: appDistribution.inAppFeedback
- name: anotherFunction
type: ...
您可以使用下列值作為alerttype
-
appDistribution.newTesterIosDevice
-
appDistribution.inAppFeedback
自訂事件觸發器 (Eventarc)
當特定事件類型發佈到特定通道時,Eventarc 觸發的函數就會運作。
有關編寫 Eventarc 觸發函數的信息,請參閱 Cloud Functions 文件中的建立和處理自訂事件觸發器。
您也可以從擴充功能發布事件,以便使用者可以將自訂邏輯插入您的擴充功能中。請參閱在擴充功能中使用開發人員提供的自訂邏輯。
函數定義(僅限第二代)
import { onCustomEventPublished } from "firebase-functions/v2/eventarc";
export const yourFunctionName = onCustomEventPublished((event) => {
// ...
});
資源聲明(擴展名.yaml)
apis:
- apiName: eventarc.googleapis.com
reason: Powers all events and triggers
- apiName: run.googleapis.com
reason: Powers 2nd-gen functions
resources:
- name: yourfunctionname
type: firebaseextensions.v1beta.v2function
properties:
# LOCATION is a user-configured parameter value specified by the user
# during installation.
location: ${param:LOCATION}
buildConfig:
runtime: nodejs16
serviceConfig:
availableMemory: 512M
timeoutSeconds: 60
eventTrigger:
eventType: firebase.extensions.storage-resize-images.v1.complete
channel: projects/${param:PROJECT_ID}/locations/us-central1/channels/firebase
- name: anotherFunction
type: ...
安裝擴充功能時該頻道必須已存在。例如,如果您依賴建立頻道的另一個擴充功能的自訂事件,請指示您的使用者先安裝該擴充功能。
上面的範例將為us-central1
區域中的「預設」Firebase 通道建立自訂事件觸發器。您可以使用參數自訂通道名稱和區域。例如:
params:
- param: EVENTARC_CHANNEL_NAME
label: Eventarc channel name
description: What is the name of the Eventarc channel.
default: firebase
type: string
required: true
resources:
- name: yourfunctionname
type: firebaseextensions.v1beta.v2function
properties:
location: ${param:LOCATION}
eventTrigger:
eventType: firebase.extensions.storage-resize-images.v1.complete
channel: projects/${param:PROJECT_ID}/locations/${param:LOCATION}/channels/${param:EVENTARC_CHANNEL_NAME}