如要開始使用 Cloud Functions,可以嘗試瀏覽本教學課程 第一步是完成必要的設定工作,並完成建立、測試 及部署兩個相關函式:
- 「add message」函式會公開可接受文字值的網址,並將該值寫入 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/v2/https");
const {onDocumentCreated} = require("firebase-functions/v2/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、PubSub、Auth 和 HTTP 可呼叫的觸發條件。您可以使用本頁未提及的工具集以互動方式測試其他類型的背景觸發事件,例如 Remote Config 和 TestLab 觸發事件。
本教學課程的下列各節將詳細說明建構步驟、 測試及部署範例
建立 Firebase 專案
-
在 Firebase 控制台中,按一下「新增專案」。
-
如要將 Firebase 資源新增至現有的 Google Cloud 專案,請輸入專案的名稱 或從下拉式選單中選取專案
-
如要建立新專案,請輸入所需的專案名稱。您也可以視需要編輯專案名稱下方顯示的專案 ID。
-
-
如果出現提示訊息,請詳閱並接受 Firebase 條款。
-
按一下「繼續」。
-
(選用) 為專案設定 Google Analytics,即可在使用下列任何 Firebase 產品時,獲得最佳體驗:
選取現有的 Google Analytics 帳戶或建立新帳戶。
如果您建立新帳戶,請選取Analytics報表位置,然後接受專案的資料共用設定和 Google Analytics 條款。
-
按一下「建立專案」。如果使用「新增 Firebase」, 現有的 Google Cloud 專案)。
Firebase 會自動為 Firebase 專案佈建資源。時間 程序完成後,系統會將你帶往 Firebase 的總覽頁面 Firebase 中。
設定環境和 Firebase CLI
Node.js
您需要 Node.js 環境才能編寫函式,並需要 Firebase CLI 才能將函式部署至 Cloud Functions 執行階段。如要安裝 Node.js 和 npm, Node 版本管理工具 建議。
安裝 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.11 版為
支援。
安裝 Python 後,請使用偏好的方法安裝 Firebase CLI。
初始化您的專案
當您初始化 Cloud Functions 的 Firebase SDK 時,會建立空白專案 內含依附元件和最精簡的程式碼範例如果您使用的是 Node.js,可以選擇使用 TypeScript 或 JavaScript 來組合函式。為了便於 教學課程中,您也需要初始化 Cloud Firestore。
如要初始化專案:
- 執行
firebase login
透過瀏覽器登入並驗證 Firebase CLI。 - 前往 Firebase 專案目錄。
- 執行
firebase init firestore
。 在本教學課程中,您可以接受預設值 並在系統提示時輸入 Firestore 規則和索引檔案的值如果您尚未在這個專案中使用 Cloud Firestore,也需要選取 Firestore 的啟動模式和位置,如開始使用 Cloud 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/v2/https");
const {onDocumentCreated} = require("firebase-functions/v2/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 會在您初始化專案時,自動為 Cloud Functions 模組安裝 Firebase Admin SDK 和 Firebase SDK。進一步瞭解如何新增第三方程式庫 專案存取權,請參閱 處理依附元件。
新增「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 大寫」函式
適用於「make 大寫」函式,請在來源檔案中加入以下這幾行程式碼:
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。
如果您沒有傳回任何內容,函式就會逾時,並傳送錯誤信號,然後重試。請參閱「同步、非同步和承諾」。
模擬函式的執行作業
Firebase Local Emulator Suite 可讓您在本機電腦上建構及測試應用程式,而非部署至 Firebase 專案。強烈建議您在開發期間進行本機測試 一部分,因為這樣可以降低編寫錯誤而失敗 在正式環境中產生費用 (例如無限迴圈)。
如要模擬函式:
執行
firebase emulators:start
,並檢查輸出內容中 Emulator Suite UI 的網址。預設值為 localhost:4000,但也可能由不同的主機代管 的 IP 位址在瀏覽器中輸入該網址,即可開啟 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
。 您可以視需要變更訊息「大寫」自訂 IP 位址 撰寫新的電子郵件訊息在瀏覽器中開啟新分頁,建立新的訊息。
查看 Emulator Suite UI 中函式的效果:
「記錄檔」分頁中應該會顯示新的記錄檔,說明 您的 HTTP 函式已成功執行:
i functions: Beginning execution of "addMessage"
i functions: Beginning execution of "makeUppercase"
「Firestore」分頁中應會顯示一份含有原始檔案的文件 訊息及大寫版本 (如果有的話) 您會看到「大寫」。
將函式部署至實際工作環境
所需函式在模擬器中正常運作後,即可繼續 包括在正式環境中部署、測試及執行注意事項 在實際工作環境中 必須採用 Blaze 定價方案。請參閱 Cloud Functions 定價。
如要完成本教學課程,請部署函式並執行函式。
執行下列指令來部署函式:
firebase deploy --only functions
執行這項指令後,Firebase CLI 會輸出任何 HTTP 函式端點的網址。您應該會在終端機中看到類似以下的文字行:
Function URL (addMessage): https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage
該網址包含您的專案 ID 和 HTTP 區域 函式。雖然您現在不需擔心 函式應將位置指定為 盡可能縮短網路延遲時間
如果發生存取錯誤,例如「無法授權存取 「專案」請檢查您的專案別名。
使用 CLI 的網址輸出新增文字查詢參數。 然後在瀏覽器中開啟:
https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage?text=uppercasemetoo
這項函式會執行並將瀏覽器重新導向至資料庫位置的 Firebase 主控台,該位置儲存文字字串。這個寫入事件會觸發「make uppercase」函式,該函式會寫入字串的大寫版本。
部署及執行函式後 您可以前往 Google Cloud 控制台查看記錄。 如果您需要在開發或實際環境中刪除函式,請使用 Firebase CLI。
在實際工作環境中,建議您最佳化函式效能和控管機制 設定要執行的執行個體數量上下限。如要進一步瞭解這些執行階段選項,請參閱「控制縮放行為」。
後續步驟
這份說明文件可協助您進一步瞭解如何 Cloud Functions的函式 以及如何 來處理 Cloud Functions 支援的所有事件類型。
如要進一步瞭解Cloud Functions,請 也可以進行下列操作: