如要開始使用 Cloud Functions,請嘗試完成本教學課程,課程會從必要的設定工作開始,並逐步建立、測試及部署兩個相關函式:
- 「新增訊息」函式會公開接受文字值的網址,並將其寫入 Cloud Firestore。
- 「轉換為大寫」函式,會在 Cloud Firestore 寫入時觸發,並將文字轉換為大寫。
我們選擇 Cloud Firestore 和 HTTP 觸發的 JavaScript 函式做為這個範例,部分原因是這些背景觸發條件可以透過 Firebase Local Emulator Suite 進行完整測試。這套工具也支援 Realtime Database、Pub/Sub、Auth 和 HTTP 可呼叫觸發條件。其他類型的背景觸發條件 (例如 Remote Config、TestLab 和 Analytics 觸發條件) 都可以使用本頁未說明的工具組進行互動式測試。
本教學課程的後續章節將詳細說明建構、測試及部署範例所需的步驟。如果您只想執行程式碼並檢查,請跳至「 查看完整程式碼範例」。
建立 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 專案總覽頁面。
設定 Node.js 和 Firebase CLI
您需要 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,請重新執行相同指令。
初始化您的專案
初始化 Cloud Functions 的 Firebase SDK 時,您會建立一個空白專案,其中包含依附元件和一些最基本的程式碼範例,並選擇使用 TypeScript 或 JavaScript 編寫函式。在本教學課程中,您也需要初始化 Cloud Firestore。
如要初始化專案,請按照下列步驟操作:
執行
firebase login,透過瀏覽器登入並驗證 Firebase CLI。前往 Firebase 專案目錄。
執行
firebase init firestore。 在本教學課程中,當系統提示您輸入 Firestore 規則和索引檔案時,您可以接受預設值。如果您尚未在這個專案中使用 Cloud Firestore,則必須按照「開始使用 Cloud Firestore」一文所述,選取 Firestore 的啟動模式和位置。執行
firebase init functions。 CLI 會提示您選擇現有的程式碼集,或初始化並命名新的程式碼集。剛開始時,預設位置的單一程式碼集就足夠;之後,隨著實作範圍擴大,您可能需要在程式碼集中整理函式。CLI 提供下列語言支援選項:
- JavaScript
- Python
- TypeScript 詳情請參閱「使用 TypeScript 編寫函式」。
在本教學課程中,請選取「JavaScript」。
CLI 提供使用 npm 安裝依附元件的選項。如果您想以其他方式管理依附元件,可以放心拒絕,但如果拒絕,則必須先執行
npm install,才能模擬或部署函式。
成功完成這些指令後,專案結構會如下所示:
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
初始化期間建立的 package.json 檔案包含重要金鑰:"engines": {"node": "16"}。這會指定用於編寫及部署函式的 Node.js 版本。您可以選取其他支援的版本。
匯入必要模組並初始化應用程式
完成設定工作後,您可以開啟來源目錄,並按照下列各節所述開始新增程式碼。在這個範例中,專案必須使用 Node require 陳述式匯入 Cloud Functions 和 Admin SDK 模組。在 index.js 檔案中新增類似下列的程式碼:
// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers. const functions = require('firebase-functions/v1'); // The Firebase Admin SDK to access Firestore. const { initializeApp } = require("firebase-admin/app"); const { getFirestore } = require("firebase-admin/firestore"); initializeApp();
這些程式碼行會載入 firebase-functions 和 firebase-admin 模組,並初始化 admin 應用程式執行個體,以便變更 Cloud Firestore。只要支援 Admin SDK (例如 FCM、Authentication 和 Firebase Realtime Database),就能使用 Cloud Functions 整合 Firebase。
初始化專案時,Firebase CLI 會自動安裝 Cloud Functions Node 模組的 Firebase 和 Firebase SDK。如要將第三方程式庫新增至專案,可以修改 package.json 並執行 npm install。詳情請參閱「處理依附元件」。
新增 addMessage() 函式
在 addMessage() 函式中,將以下幾行程式碼新增至 index.js:
// Take the text parameter passed to this HTTP endpoint and insert it into // Firestore under the path /messages/:documentId/original exports.addMessage = functions.https.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.` }); });
addMessage() 函式是 HTTP 端點。對端點提出的任何要求,都會導致 ExpressJS 樣式的要求和回應物件傳遞至 onRequest() 回呼。
HTTP 函式是同步函式 (類似可呼叫函式),因此您應盡快傳送回應,並使用 Cloud Firestore 延遲工作。addMessage() HTTP 函式會將文字值傳遞至 HTTP 端點,並將其插入路徑 /messages/:documentId/original 下方的資料庫。
新增 makeUppercase() 函式
在 makeUppercase() 函式中,將以下幾行程式碼新增至 index.js:
// Listens for new messages added to /messages/:documentId/original and creates an // uppercase version of the message to /messages/:documentId/uppercase exports.makeUppercase = functions.firestore .document("/messages/{documentId}") .onCreate((snap, context) => { // Grab the current value of what was written to Firestore. const original = snap.data().original; // Access the parameter `{documentId}` with `context.params` functions.logger.log("Uppercasing", context.params.documentId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to Firestore. // Setting an 'uppercase' field in Firestore document returns a Promise. return snap.ref.set({ uppercase }, { merge: true }); });
makeUppercase() 函式會在 Cloud Firestore 寫入時執行。ref.set 函式會定義要監聽的文件。基於效能考量,請盡可能具體。
大括號 (例如 {documentId}) 會包住「參數」,也就是在回呼中公開相符資料的萬用字元。
每當新增訊息時,Cloud Firestore 都會觸發 onCreate() 回呼。
事件導向函式 (例如 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 函式addMessage()的網址。這與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」(記錄) 分頁中,您應該會看到新的記錄,指出
addMessage()和makeUppercase()函式已執行:i functions: Beginning execution of "addMessage"i functions: Beginning execution of "makeUppercase"在「Firestore」分頁中,您應該會看到一份文件,其中包含原始訊息和大寫版本的訊息 (如果原始訊息是「uppercaseme」,您會看到「UPPERCASEME」)。
將函式部署至正式環境
函式在模擬器中正常運作後,即可在正式環境中部署、測試及執行。請注意,如要部署至 Node.js 14 執行階段環境,專案必須採用 Blaze 定價方案。請參閱 Cloud Functions 定價。
如要完成教學課程,請部署函式,然後執行 addMessage() 來觸發 makeUppercase()。
執行下列指令來部署函式:
firebase deploy --only functions
執行這項指令後,Firebase CLI 會輸出任何 HTTP 函式端點的網址。終端機中應該會顯示類似下列的訊息:
Function URL (addMessage): https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage網址包含專案 ID 和 HTTP 函式的區域。雖然您現在不必擔心這個問題,但部分實際工作環境 HTTP 函式應指定位置,盡可能縮短網路延遲時間。
如果遇到「無法授權存取專案」等存取錯誤,請嘗試檢查專案別名。
使用 CLI 輸出的
addMessage()網址,新增文字查詢參數,然後在瀏覽器中開啟:https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage?text=uppercasemetoo函式會執行並將瀏覽器重新導向至 Firebase 控制台,前往儲存文字字串的資料庫位置。這項寫入事件會觸發
makeUppercase(),進而寫入字串的大寫版本。
部署並執行函式後,您可以在 Google Cloud 控制台中查看記錄。如需在開發或正式環境中刪除函式,請使用 Firebase CLI。
在正式環境中,您可以設定要執行的執行個體數量上下限,藉此最佳化函式效能並控管成本。如要進一步瞭解這些執行階段選項,請參閱「控管資源調度行為」。
查看完整程式碼範例
以下是完整的 functions/index.js,其中包含 addMessage() 和 makeUppercase() 函式。這些函式可讓您將參數傳遞至 HTTP 端點,將值寫入 Cloud Firestore,然後將字串中的所有字元轉換為大寫。
// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers. const functions = require('firebase-functions/v1'); // 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 = functions.https.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 creates an // uppercase version of the message to /messages/:documentId/uppercase exports.makeUppercase = functions.firestore .document("/messages/{documentId}") .onCreate((snap, context) => { // Grab the current value of what was written to Firestore. const original = snap.data().original; // Access the parameter `{documentId}` with `context.params` functions.logger.log("Uppercasing", context.params.documentId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to Firestore. // Setting an 'uppercase' field in Firestore document returns a Promise. return snap.ref.set({ uppercase }, { merge: true }); });
後續步驟
本說明文件將進一步說明如何 管理 Cloud Functions 的函式 ,以及如何 處理 Cloud Functions 支援的所有事件類型。
如要進一步瞭解 Cloud Functions,您也可以執行下列操作:
- 瞭解 Cloud Functions 的用途。
- 試試 Cloud Functions 程式碼實驗室。
- 查看並執行 GitHub 上的程式碼範例