建立擴充功能時,您會使用 Cloud Functions 編寫邏輯,與編寫只會在自己專案中使用的函式非常相似。您可以在 extension.yaml 檔案中宣告函式,使用者安裝擴充功能時,這些函式就會部署到他們的專案中。
如要瞭解如何使用 Cloud Functions,請參閱 Cloud Functions 說明文件。
第 1 代和第 2 代 Cloud Functions
Firebase 支援第 1 代和第 2 代Cloud Functions。不過,Firebase 擴充功能目前對某些觸發條件類型設有限制,您只能搭配使用特定世代的 Cloud Functions。因此,許多擴充功能會混合使用第 1 代和第 2 代函式。
下表列出各觸發條件類型是否支援函式生成功能。
特殊注意事項
部分函式定義需要您指定資訊,而這些資訊也會在
extension.yaml檔案中指定。舉例來說,Cloud Firestore 有document()方法,可指定要監看的檔案模式,而extension.yaml中的對應宣告則有resource欄位,可指定相同模式。在這些情況下,系統會使用
extension.yaml檔案中指定的設定,並忽略函式定義中指定的設定。為了方便記錄,無論如何,一般都會在函式定義中指定設定值。本頁的範例遵循這個模式。
第 1 代 SDK 具有
functions.config()方法和functions:config:setCLI 指令,可用於處理第 1 代函式中的參數化值。Cloud Functions這項技術已在 Cloud Functions 中淘汰,且完全無法在擴充功能中使用。請改用functions.params模組 (建議) 或process.env。
使用 TypeScript
開發擴充功能時,大部分的說明文件都會介紹使用 JavaScript 進行 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 要求呼叫函式」。
函式定義 (僅限第 1 代)
import { https } from "firebase-functions/v1";
export const yourFunctionName = https.onRequest(async (req, resp) => {
// ...
});
資源宣告 (extension.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
runtime: nodejs16
httpsTrigger: {}
- name: anotherFunction
type: ...
可呼叫函式
可呼叫函式與 HTTP 觸發函式類似,但實作的通訊協定可讓您從用戶端程式碼輕鬆呼叫。
如要瞭解如何使用可呼叫函式,請參閱 Cloud Functions 說明文件中的「從應用程式呼叫函式」。
函式定義 (僅限第 1 代)
import { https } from "firebase-functions/v1";
export const yourFunctionName = https.onCall(async (data, context) => {
// ...
});
資源宣告 (extension.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
runtime: nodejs16
httpsTrigger: {}
- name: anotherFunction
type: ...
排定函式觸發條件
排程函式會根據可自訂的排程重複執行。
如要瞭解如何編寫排程函式,請參閱 Cloud Functions 說明文件中的「排程函式」一文。
函式定義 (僅限第 1 代)
import { pubsub } from "firebase-functions/v1";
export const yourFunctionName = pubsub.schedule("every 6 hours").onRun((context) => {
// ...
});
資源宣告 (extension.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說明文件中的「使用 Cloud Tasks 將函式加入佇列」。
函式定義 (僅限第 1 代)
import { tasks } from "firebase-functions/v1";
export const yourFunctionName = tasks.taskQueue().onDispatch(async (data, context) => {
// ...
});
資源宣告 (extension.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 觸發的函式。
如要瞭解如何編寫 Analytics 觸發函式,請參閱 Cloud Functions 說明文件中的 Google Analytics 觸發條件。
函式定義 (僅限第 1 代)
import { analytics } from "firebase-functions/v1";
export const yourFunctionName = analytics.event("event_name").onLog((event, context) => {
// ...
});
資源宣告 (extension.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
Authentication
建立或刪除使用者時,系統會執行驗證觸發函式。
如要瞭解如何編寫以驗證觸發的函式,請參閱 Cloud Functions 說明文件中的「Firebase 驗證觸發條件」。
函式定義 (僅限第 1 代)
import { auth } from "firebase-functions/v1";
export const yourFunctionName = auth.user().onCreate((user, context) => {
// ...
});
export const yourFunctionName2 = auth.user().onDelete((user, context) => {
// ...
});
資源宣告 (extension.yaml)
resources:
- name: yourFunctionName
type: firebaseextensions.v1beta.function
properties:
eventTrigger:
eventType: providers/firebase.auth/eventTypes/user.create
resource: projects/${PROJECT_ID}
- name: anotherFunction
type: ...
下表說明如何指定各支援的 Authentication 事件類型:
| Cloud Functions 事件觸發條件 | eventType |
說明 |
|---|---|---|
onCreate() |
providers/firebase.auth/eventTypes/user.create |
已建立新使用者 |
onDelete() |
providers/firebase.auth/eventTypes/user.delete |
已刪除使用者 |
Cloud Firestore
當文件建立、更新或刪除時,系統會執行 Cloud Firestore 觸發的函式。
如要瞭解如何編寫由 Firestore 觸發的函式,請參閱 Cloud Functions 說明文件中的「Cloud Firestore 觸發條件」。
函式定義 (僅限第 1 代)
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.
// ...
});
資源宣告 (extension.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 觸發函式。
如要瞭解如何編寫由 Pub/Sub 觸發的函式,請參閱 Cloud Functions 說明文件中的「Pub/Sub 觸發條件」。
函式定義 (僅限第 1 代)
import { pubsub } from "firebase-functions/v1";
export const yourFunctionName = pubsub.topic("topic_name").onPublish((message, context) => {
// ...
});
資源宣告 (extension.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
Realtime Database
當建立、更新或刪除符合指定模式的路徑時,系統會執行以 Realtime Database 觸發的函式。
如要瞭解如何編寫 RTDB 觸發函式,請參閱 Cloud Functions 說明文件中的「即時資料庫觸發條件」。
函式定義 (僅限第 1 代)
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.
// ...
});
資源宣告 (extension.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
Remote Config
專案的參數範本更新時,系統會執行遠端設定觸發的函式。
如要瞭解如何編寫遠端設定觸發的函式,請參閱 Cloud Functions 說明文件中的「遠端設定觸發條件」。
函式定義 (僅限第 1 代)
import { remoteConfig } from "firebase-functions/v1";
export const yourFunctionName = remoteConfig.onUpdate((version, context) => {
// ...
});
資源宣告 (extension.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 Storage 觸發的函式。
如要瞭解如何編寫由 Storage 觸發的函式,請參閱 Cloud Functions 說明文件中的「Cloud Storage 觸發條件」。
函式定義 (僅限第 1 代)
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) => {
// ...
});
資源宣告 (extension.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
Test Lab
測試矩陣完成測試後,系統會執行 Test Lab 觸發的函式。
如要瞭解如何編寫 Test Lab 觸發的函式,請參閱 Cloud Functions 說明文件中的「Firebase Test Lab 觸發條件」。
函式定義 (僅限第 1 代)
import { testLab } from "firebase-functions/v1";
export const yourFunctionName = testLab.testMatrix().onComplete((matrix, context) => {
// ...
});
資源宣告 (extension.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 快訊觸發條件」。
函式定義 (僅限第 2 代)
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) => {
// ...
});
資源宣告 (extension.yaml)
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.newFatalIssuecrashlytics.newNonfatalIssuecrashlytics.regressioncrashlytics.stabilityDigestcrashlytics.velocitycrashlytics.newAnrIssue
Performance Monitoring 警示觸發條件
Performance Monitoring 發布快訊時,系統會執行 Performance Monitoring 觸發的函式。
如要瞭解如何編寫由快訊觸發的函式,請參閱 Cloud Functions 說明文件中的「Firebase 快訊觸發條件」。
函式定義 (僅限第 2 代)
import { onThresholdAlertPublished } from "firebase-functions/v2/alerts/performance";
export const yourFunctionName = onThresholdAlertPublished((event) => {
// ...
});
資源宣告 (extension.yaml)
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 發布快訊時,系統會執行 App Distribution 觸發的函式。
如要瞭解如何編寫由快訊觸發的函式,請參閱 Cloud Functions 說明文件中的「Firebase 快訊觸發條件」。
函式定義 (僅限第 2 代)
import {
onNewTesterIosDevicePublished,
onInAppFeedbackPublished
} from "firebase-functions/v2/alerts/appDistribution";
export const yourFunctionName = onNewTesterIosDevicePublished((event) => {
// ...
});
export const yourFunctionName2 = onInAppFeedbackPublished((event) => {
// ...
});
資源宣告 (extension.yaml)
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.newTesterIosDeviceappDistribution.inAppFeedback
自訂事件觸發條件 (Eventarc)
當特定事件類型發布至特定管道時,就會執行 Eventarc 觸發的函式。
如要瞭解如何編寫 Eventarc 觸發的函式,請參閱 Cloud Functions 說明文件中的「建立及處理自訂事件觸發條件」。
您也可以從擴充功能發布事件,讓使用者將自訂邏輯插入擴充功能。請參閱「在擴充功能中使用開發人員提供的自訂邏輯」。
函式定義 (僅限第 2 代)
import { onCustomEventPublished } from "firebase-functions/v2/eventarc";
export const yourFunctionName = onCustomEventPublished((event) => {
// ...
});
資源宣告 (extension.yaml)
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 地區的「default」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}