如要開始使用 Cloud Functions,請嘗試完成本教學課程,從必要的設定工作開始,逐步建立、測試及部署兩項相關函式:
- 「新增訊息」函式會公開接受文字值的網址,並將其寫入 Cloud Firestore。
- 「轉換為大寫」函式,會在 Cloud Firestore 寫入時觸發,並將文字轉換為大寫。
以下是包含函式的完整程式碼範例:
Node.js
// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const {logger} = require("firebase-functions");
const {onRequest} = require("firebase-functions/https");
const {onDocumentCreated} = require("firebase-functions/firestore");
// The Firebase Admin SDK to access Firestore.
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");
initializeApp();
// Take the text parameter passed to this HTTP endpoint and insert it into
// Firestore under the path /messages/:documentId/original
exports.addmessage = onRequest(async (req, res) => {
// Grab the text parameter.
const original = req.query.text;
// Push the new message into Firestore using the Firebase Admin SDK.
const writeResult = await getFirestore()
.collection("messages")
.add({original: original});
// Send back a message that we've successfully written the message
res.json({result: `Message with ID: ${writeResult.id} added.`});
});
// Listens for new messages added to /messages/:documentId/original
// and saves an uppercased version of the message
// to /messages/:documentId/uppercase
exports.makeuppercase = onDocumentCreated("/messages/{documentId}", (event) => {
// Grab the current value of what was written to Firestore.
const original = event.data.data().original;
// Access the parameter `{documentId}` with `event.params`
logger.log("Uppercasing", event.params.documentId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing
// asynchronous tasks inside a function
// such as writing to Firestore.
// Setting an 'uppercase' field in Firestore document returns a Promise.
return event.data.ref.set({uppercase}, {merge: true});
});
Python
# The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
from firebase_functions import firestore_fn, https_fn
# The Firebase Admin SDK to access Cloud Firestore.
from firebase_admin import initialize_app, firestore
import google.cloud.firestore
app = initialize_app()
@https_fn.on_request()
def addmessage(req: https_fn.Request) -> https_fn.Response:
"""Take the text parameter passed to this HTTP endpoint and insert it into
a new document in the messages collection."""
# Grab the text parameter.
original = req.args.get("text")
if original is None:
return https_fn.Response("No text parameter provided", status=400)
firestore_client: google.cloud.firestore.Client = firestore.client()
# Push the new message into Cloud Firestore using the Firebase Admin SDK.
_, doc_ref = firestore_client.collection("messages").add({"original": original})
# Send back a message that we've successfully written the message
return https_fn.Response(f"Message with ID {doc_ref.id} added.")
@firestore_fn.on_document_created(document="messages/{pushId}")
def makeuppercase(event: firestore_fn.Event[firestore_fn.DocumentSnapshot | None]) -> None:
"""Listens for new documents to be added to /messages. If the document has
an "original" field, creates an "uppercase" field containg the contents of
"original" in upper case."""
# Get the value of "original" if it exists.
if event.data is None:
return
try:
original = event.data.get("original")
except KeyError:
# No "original" field, so do nothing.
return
# Set the "uppercase" field.
print(f"Uppercasing {event.params['pushId']}: {original}")
upper = original.upper()
event.data.reference.update({"uppercase": upper})
關於本教學課程
我們選擇 Cloud Firestore 和 HTTP 觸發函式做為這個範例,部分原因是這些背景觸發條件可以透過 Firebase Local Emulator Suite 進行完整測試。這組工具也支援 Realtime Database、Cloud Storage、Pub/Sub、Auth 和 HTTP 可呼叫觸發條件。其他類型的背景觸發條件 (例如 Remote Config 和 TestLab 觸發條件),可以使用本頁未說明的工具組進行互動式測試。
本教學課程的後續章節將詳細說明建構、測試及部署範例所需的步驟。
建立 Firebase 專案
第一次使用 Firebase 或 Cloud
如果您是 Firebase 或 Google Cloud 的新手,請按照下列步驟操作。
如要建立全新的 Firebase 專案 (及其基礎 Google Cloud 專案),也可以按照下列步驟操作。
- 登入 Firebase 控制台。
- 按一下按鈕,建立新的 Firebase 專案。
-
在文字欄位中輸入專案名稱。
如果您隸屬於 Google Cloud 組織,可以視需要選取要在哪個資料夾中建立專案。
- 如果出現提示訊息,請詳閱並接受《Firebase 條款》,然後點按「繼續」。
- (選用) 在 Firebase 控制台中啟用 AI 輔助功能 (稱為「Gemini in Firebase」),協助您快速上手並簡化開發程序。
-
(選用) 為專案設定 Google Analytics,以便在使用下列 Firebase 產品時享有最佳體驗:Firebase A/B Testing、Cloud Messaging、Crashlytics、In-App Messaging 和 Remote Config (包括個人化)。
選取現有的 Google Analytics 帳戶或建立新帳戶。如要建立新帳戶,請選取Analytics報表位置,然後接受專案的資料共用設定和Google Analytics條款。
- 按一下「Create project」(建立專案)。
Firebase 會建立專案、佈建一些初始資源,並啟用重要 API。程序完成後,系統會將您導向 Firebase 控制台中的 Firebase 專案總覽頁面。
現有雲端專案
如要開始搭配現有 Google Cloud 專案使用 Firebase,請按照下列步驟操作。進一步瞭解如何將 Firebase 新增至現有的 Google Cloud 專案,並排解相關問題。
- 使用可存取現有 Google Cloud 專案的帳戶登入 Firebase 控制台。
- 按一下按鈕,建立新的 Firebase 專案。
- 在頁面底部點按「將 Firebase 新增到 Google Cloud 雲端專案」。
- 在文字欄位中,開始輸入現有專案的專案名稱,然後從顯示的清單中選取專案。
- 按一下「Open project」(開啟專案)。
- 如果出現提示訊息,請詳閱並接受《Firebase 條款》,然後點按「繼續」。
- (選用) 在 Firebase 控制台中啟用 AI 輔助功能 (稱為「Gemini in Firebase」),協助您快速上手並簡化開發程序。
-
(選用) 為專案設定 Google Analytics,以便在使用下列 Firebase 產品時享有最佳體驗:Firebase A/B Testing、Cloud Messaging、Crashlytics、In-App Messaging 和 Remote Config (包括個人化)。
選取現有的 Google Analytics 帳戶或建立新帳戶。如要建立新帳戶,請選取Analytics報表位置,然後接受專案的資料共用設定和Google Analytics條款。
- 按一下「Add Firebase」。
Firebase 會將 Firebase 新增至現有專案。程序完成後,系統會將您導向 Firebase 控制台中的 Firebase 專案總覽頁面。
設定環境和 Firebase CLI
Node.js
您需要 Node.js 環境才能編寫函式,並需要 Firebase CLI 才能將函式部署至 Cloud Functions 執行階段。如要安裝 Node.js 和 npm,建議使用 Node Version Manager。
安裝 Node.js 和 npm 後,請透過偏好的方法安裝 Firebase CLI。如要透過 npm 安裝 CLI,請使用:
npm install -g firebase-tools
這會安裝全域可用的 firebase 指令。如果指令失敗,您可能需要變更 npm 權限。如要更新至最新版本 firebase-tools,請重新執行相同指令。
Python
您需要 Python 環境來編寫函式,並需要 Firebase CLI 將函式部署至 Cloud Functions 執行階段。建議使用 venv 隔離依附元件。支援 Python 3.10 至 3.13 版,預設執行階段為 3.13。
安裝 Python 後,請透過偏好的方法安裝 Firebase CLI。
初始化您的專案
初始化 Cloud Functions 的 Firebase SDK 時,系統會建立一個空白專案,其中包含依附元件和一些最基本的程式碼範例。如果使用 Node.js,可以選擇 TypeScript 或 JavaScript 來編寫函式。在本教學課程中,您也需要初始化 Cloud Firestore。
如要初始化專案,請按照下列步驟操作:
- 執行
firebase login,透過瀏覽器登入並驗證 Firebase CLI。 - 前往 Firebase 專案目錄。
- 執行
firebase init firestore。 在本教學課程中,當系統提示您輸入 Firestore 規則和索引檔案時,您可以接受預設值。如果您尚未在這個專案中使用 Cloud Firestore,則必須按照「開始使用 Cloud Firestore」一文所述,選取 Firestore 的啟動模式和位置。 - 執行
firebase init functions。 CLI 會提示您選擇現有的程式碼集,或初始化並命名新的程式碼集。剛開始時,預設位置的單一程式碼集就足夠;之後,隨著實作範圍擴大,您可能需要在程式碼集中整理函式。 CLI 支援下列語言:
- JavaScript
- TypeScript
- Python
在本教學課程中,請選取「JavaScript」或「Python」。如要使用 TypeScript 編寫,請參閱「使用 TypeScript 編寫函式」。
CLI 提供安裝依附元件的選項。如果您想以其他方式管理依附元件,可以放心拒絕。
成功完成這些指令後,專案結構會如下所示:
Node.js
myproject
+- .firebaserc # Hidden file that helps you quickly switch between
| # projects with `firebase use`
|
+- firebase.json # Describes properties for your project
|
+- functions/ # Directory containing all your functions code
|
+- .eslintrc.json # Optional file containing rules for JavaScript linting.
|
+- package.json # npm package file describing your Cloud Functions code
|
+- index.js # Main source file for your Cloud Functions code
|
+- node_modules/ # Directory where your dependencies (declared in
# package.json) are installed
如果是 Node.js,初始化期間建立的 package.json 檔案會包含重要金鑰:"engines": {"node": "18"}。這會指定編寫及部署函式時使用的 Node.js 版本。您可以選取其他支援的版本。
Python
myproject
+- .firebaserc # Hidden file that helps you quickly switch between
| # projects with `firebase use`
|
+- firebase.json # Describes properties for your project
|
+- functions/ # Directory containing all your functions code
|
+- main.py # Main source file for your Cloud Functions code
|
+- requirements.txt # List of the project's modules and packages
|
+- venv/ # Directory where your dependencies are installed
匯入必要模組並初始化應用程式
完成設定工作後,您可以開啟來源目錄,並按照下列各節所述開始新增程式碼。在這個範例中,專案必須匯入 Cloud Functions 和 Admin SDK 模組。在來源檔案中加入類似下列的程式碼:
Node.js
// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const {logger} = require("firebase-functions");
const {onRequest} = require("firebase-functions/https");
const {onDocumentCreated} = require("firebase-functions/firestore");
// The Firebase Admin SDK to access Firestore.
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");
initializeApp();
Python
# The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
from firebase_functions import firestore_fn, https_fn
# The Firebase Admin SDK to access Cloud Firestore.
from firebase_admin import initialize_app, firestore
import google.cloud.firestore
app = initialize_app()
這些程式碼行會載入必要模組,並初始化 admin 應用程式執行個體,以便變更 Cloud Firestore。只要支援 Admin SDK (例如 FCM、Authentication 和 Firebase Realtime Database),就能使用 Cloud Functions 整合 Firebase,功能十分強大。
初始化專案時,Firebase CLI 會自動安裝 Firebase Admin SDK 和 Cloud Functions 模組的 Firebase SDK。如要進一步瞭解如何將第三方資料庫新增至專案,請參閱「處理依附元件」。
新增「add message」函式
針對「add message」函式,請在來源檔案中加入下列幾行程式碼:
Node.js
// Take the text parameter passed to this HTTP endpoint and insert it into
// Firestore under the path /messages/:documentId/original
exports.addmessage = onRequest(async (req, res) => {
// Grab the text parameter.
const original = req.query.text;
// Push the new message into Firestore using the Firebase Admin SDK.
const writeResult = await getFirestore()
.collection("messages")
.add({original: original});
// Send back a message that we've successfully written the message
res.json({result: `Message with ID: ${writeResult.id} added.`});
});
Python
@https_fn.on_request()
def addmessage(req: https_fn.Request) -> https_fn.Response:
"""Take the text parameter passed to this HTTP endpoint and insert it into
a new document in the messages collection."""
# Grab the text parameter.
original = req.args.get("text")
if original is None:
return https_fn.Response("No text parameter provided", status=400)
firestore_client: google.cloud.firestore.Client = firestore.client()
# Push the new message into Cloud Firestore using the Firebase Admin SDK.
_, doc_ref = firestore_client.collection("messages").add({"original": original})
# Send back a message that we've successfully written the message
return https_fn.Response(f"Message with ID {doc_ref.id} added.")
「新增訊息」函式是 HTTP 端點。對端點提出的任何要求,都會導致要求和回應物件傳遞至平台的請求處理常式 (onRequest() 或 on_request)。
HTTP 函式是同步函式 (類似於可呼叫函式),因此您應盡快傳送回應,並使用 Cloud Firestore 延遲工作。「新增訊息」HTTP 函式會將文字值傳遞至 HTTP 端點,並將其插入路徑 /messages/:documentId/original 下的資料庫。
新增「轉換為大寫」函式
針對「make uppercase」函式,請在來源檔案中加入下列程式碼:
Node.js
// Listens for new messages added to /messages/:documentId/original
// and saves an uppercased version of the message
// to /messages/:documentId/uppercase
exports.makeuppercase = onDocumentCreated("/messages/{documentId}", (event) => {
// Grab the current value of what was written to Firestore.
const original = event.data.data().original;
// Access the parameter `{documentId}` with `event.params`
logger.log("Uppercasing", event.params.documentId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing
// asynchronous tasks inside a function
// such as writing to Firestore.
// Setting an 'uppercase' field in Firestore document returns a Promise.
return event.data.ref.set({uppercase}, {merge: true});
});
Python
@firestore_fn.on_document_created(document="messages/{pushId}")
def makeuppercase(event: firestore_fn.Event[firestore_fn.DocumentSnapshot | None]) -> None:
"""Listens for new documents to be added to /messages. If the document has
an "original" field, creates an "uppercase" field containg the contents of
"original" in upper case."""
# Get the value of "original" if it exists.
if event.data is None:
return
try:
original = event.data.get("original")
except KeyError:
# No "original" field, so do nothing.
return
# Set the "uppercase" field.
print(f"Uppercasing {event.params['pushId']}: {original}")
upper = original.upper()
event.data.reference.update({"uppercase": upper})
當 Cloud Firestore 寫入時,系統會執行「make uppercase」函式,定義要監聽的文件。基於效能考量,請盡可能具體。
大括號 (例如 {documentId}) 會包住「參數」,也就是在回呼中公開相符資料的萬用字元。每當有新訊息加入時,Cloud Firestore 就會觸發回呼。
在 Node.js 中,Cloud Firestore 事件等事件導向函式是非同步的。回呼函式應傳回 null、物件或 Promise。如果未傳回任何內容,函式會逾時、發出錯誤信號,並重試。請參閱「同步、非同步和 Promise」。
模擬函式執行
Firebase Local Emulator Suite 可讓您在本機電腦上建構及測試應用程式,而不必部署至 Firebase 專案。強烈建議您在開發期間進行本機測試,部分原因是這能降低程式碼錯誤的風險,避免在正式環境中產生潛在費用 (例如無限迴圈)。
如要模擬函式,請按照下列步驟操作:
執行
firebase emulators:start,並檢查輸出內容,找出 Emulator Suite UI 的網址。預設為 localhost:4000,但可能託管於電腦上的其他通訊埠。在瀏覽器中輸入該網址,即可開啟 Emulator Suite UI。查看
firebase emulators:start指令的輸出內容,找出 HTTP 函式的網址。這與http://localhost:5001/MY_PROJECT/us-central1/addMessage類似,但有以下差異:MY_PROJECT會替換為您的專案 ID。- 本機電腦上的通訊埠可能不同。
在函式網址結尾加上查詢字串
?text=uppercaseme。如下所示:http://localhost:5001/MY_PROJECT/us-central1/addMessage?text=uppercaseme。 您可以視需要將訊息「uppercaseme」變更為自訂訊息。在瀏覽器的新分頁中開啟網址,建立新訊息。
在 Emulator Suite UI 中查看函式的效果:
在「Logs」(記錄) 分頁中,您應該會看到新的記錄,指出 HTTP 函式已成功執行:
i functions: Beginning execution of "addMessage"i functions: Beginning execution of "makeUppercase"在「Firestore」分頁中,您應該會看到一份文件,其中包含原始訊息和大寫版本的訊息 (如果原始訊息是「uppercaseme」,您會看到「UPPERCASEME」)。
將函式部署至正式環境
函式在模擬器中正常運作後,您就可以在正式環境中部署、測試及執行函式。請注意,如要在正式環境中部署,專案必須採用 Blaze 定價方案。請參閱 Cloud Functions 定價。
如要完成教學課程,請部署並執行函式。
執行下列指令來部署函式:
firebase deploy --only functions
執行這項指令後,Firebase CLI 會輸出任何 HTTP 函式端點的網址。終端機應會顯示類似下方的行:
Function URL (addMessage): https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage網址包含專案 ID 和 HTTP 函式的區域。雖然您現在不必擔心這個問題,但部分正式版 HTTP 函式應指定位置,盡可能縮短網路延遲時間。
如果遇到存取錯誤,例如「無法授權存取專案」,請嘗試檢查專案別名。
使用 CLI 輸出的網址,新增文字查詢參數,然後在瀏覽器中開啟:
https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage?text=uppercasemetoo函式會執行並將瀏覽器重新導向至儲存文字字串的資料庫位置 Firebase 控制台。這項寫入事件會觸發「轉換為大寫」函式,將字串轉換為大寫版本。
部署並執行函式後,您可以在 Google Cloud 控制台中查看記錄。如需在開發或正式環境中刪除函式,請使用 Firebase CLI。
在正式環境中,您可以設定要執行的執行個體數量上下限,藉此最佳化函式效能並控管成本。如要進一步瞭解這些執行階段選項,請參閱「控管資源調度行為」。
後續步驟
本文件將進一步說明如何 管理 Cloud Functions 的函式,以及如何處理 Cloud Functions 支援的所有事件類型。
如要進一步瞭解 Cloud Functions,也可以採取下列做法:
- 瞭解 Cloud Functions 的用途。
- 試試 Cloud Functions 程式碼實驗室。
- 查看並執行 GitHub 上的程式碼範例