開始使用:編寫、測試及部署第一個函式


如要開始使用 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/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 本機模擬器套件。這個工具組 也支援即時資料庫、Cloud Storage PubSub、Auth 和 HTTP 可呼叫觸發條件。其他類型的背景觸發條件 例如遠端設定和 TestLab 觸發條件 使用工具組進行交互測試 加以說明。

本教學課程的下列各節將詳細說明建構步驟、 測試及部署範例

建立 Firebase 專案

  1. Firebase 控制台,按一下「新增專案」

    • 如要將 Firebase 資源新增至現有的 Google Cloud 專案,請輸入 或從下拉式選單中選取專案

    • 如要建立新專案,請輸入所需專案名稱。您也可以選擇 編輯顯示在專案名稱下方的專案 ID。

  2. 如果出現提示訊息,請詳閱並接受 Firebase 條款

  3. 點選「繼續」

  4. (選用) 為專案設定 Google Analytics, ,使用下列任一 Firebase 產品來獲得最佳體驗:

    選取現有項目 Google Analytics 帳戶 或建立新帳戶

    如果您建立新帳戶,請選取 Analytics 報表位置,然後接受 專案的資料共用設定和 Google Analytics 條款。

  5. 按一下「建立專案」。如果使用「新增 Firebase」, 或現有 Google Cloud 專案

Firebase 會自動為你的 Firebase 專案佈建資源。時間 程序完成後,系統會將你帶往 Firebase 的總覽頁面 專案。

設定環境和 Firebase CLI

Node.js

您需要 Node.js 環境才能寫入函式。 而且您需要 Firebase CLI,才能將函式部署至 Cloud Functions 執行階段如要安裝 Node.js 和 npmNode 版本管理工具 建議。

安裝 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。

如要初始化專案:

  1. 執行 firebase login 透過瀏覽器登入並驗證 Firebase CLI
  2. 前往 Firebase 專案目錄。
  3. 執行 firebase init firestore。 在本教學課程中,您可以接受預設值 並在系統提示時輸入 Firestore 規則和索引檔案的值如果沒用過 這項專案中的 Cloud Firestore 必須按照 開始使用 Cloud Firestore
  4. 執行 firebase init functions。 CLI 會提示您選擇現有項目 或是初始化並命名新的程式碼集。才剛開始 只需在預設位置僅保留一個程式碼集即可; 隨著實作範圍擴大 要在程式碼集中整理函式
  5. CLI 提供下列語言支援選項:

    • JavaScript
    • TypeScript
    • Python

    在本教學課程中,請選取「JavaScript」或「Python」。編寫者: TypeScript,請參閱使用 TypeScript 編寫函式

  6. 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"}。這會指定 讓您快速編寫及部署函式你可以 選取其他支援的版本

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()

這行程式碼會載入必要模組 初始化可進行 Cloud Firestore 變更的 admin 應用程式執行個體。 凡是提供 Admin SDK 支援服務的國家/地區 適用於 FCM、驗證和 Firebase 即時資料庫 以強大的 Cloud Functions 整合 Firebase。

Firebase CLI 會自動套用 在初始化時安裝 Cloud Functions 模組專用的 Firebase Admin SDK 和 Firebase SDK 。進一步瞭解如何新增第三方程式庫 專案存取權,請參閱 處理依附元件

新增「新增訊息」函式

針對「新增訊息」函式,請在來源檔案中加入以下這幾行程式碼:

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 時執行 定義要聆聽的文件基於成效考量 請盡可能具體說明

括號,例如 {documentId},周圍是「參數」。萬用字元 ,在回呼中公開相符的資料。Cloud Firestore 會觸發 回呼。

在 Node.js 中,事件導向函式 (例如 Cloud Firestore 事件) 非同步顯示回呼函式應傳回 null、物件、 或 Promise。 如果您沒有傳回任何值,函式就會逾時、表示錯誤,以及 重試。請參閱同步處理、非同步和 Promise

模擬函式的執行作業

Firebase 本機模擬器套件 可讓您在本機電腦上建構及測試應用程式,不必部署到 Firebase 專案強烈建議您在開發期間進行本機測試 一部分,因為這樣可以降低編寫錯誤而失敗 在正式環境中產生費用 (例如無限迴圈)。

如要模擬函式:

  1. 執行 firebase emulators:start 並檢查網址的輸出內容 模擬器套件使用者介面預設值為 localhost:4000,但也可能由不同的主機代管 的 IP 位址在瀏覽器中輸入該網址即可開啟 模擬器套件 UI。

  2. 查看 firebase emulators:start 的輸出內容 指令 HTTP 函式的回應中看起來會像這樣 http://localhost:5001/MY_PROJECT/us-central1/addMessage,但以下情況除外:

    1. 系統會將 MY_PROJECT 替換為您的專案 ID。
    2. 本機電腦上的通訊埠可能不同。
  3. 將查詢字串 ?text=uppercaseme 加到函式網址的結尾。 如下所示: http://localhost:5001/MY_PROJECT/us-central1/addMessage?text=uppercaseme。 您可以視需要變更訊息「大寫」自訂 IP 位址 撰寫新的電子郵件訊息

  4. 在瀏覽器中開啟新分頁,建立新的訊息。

  5. 在模擬器套件 UI 中查看函式的效果:

    1. 「記錄檔」分頁中應該會顯示新的記錄檔,說明 您的 HTTP 函式已成功執行:

      i functions: Beginning execution of "addMessage"

      i functions: Beginning execution of "makeUppercase"

    2. 「Firestore」分頁中應會顯示一份含有原始檔案的文件 訊息及大寫版本 (如果有的話) 您會看到「大寫」。

將函式部署至正式環境

所需函式在模擬器中正常運作後,即可繼續 包括在正式環境中部署、測試及執行注意事項 在實際工作環境中 必須採用 Blaze 定價方案。詳情請見 Cloud Functions 定價

如要完成教學課程,請部署函式,然後執行 具體做法是指示 Kubernetes 建立並維護 一或多個代表這些 Pod 的物件

  1. 執行下列指令來部署函式:

     firebase deploy --only functions
     

    執行這個指令後,Firebase CLI 會輸出任何 HTTP 函式 端點。終端機中應該會顯示類似下方的行:

    Function URL (addMessage): https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage
    

    該網址包含您的專案 ID 和 HTTP 區域 函式。雖然您現在不需擔心 函式應將位置指定為 盡可能縮短網路延遲時間

    如果發生存取錯誤,例如「無法授權存取 「專案」請檢查您的專案別名

  2. 使用 CLI 的網址輸出新增文字查詢參數。 然後在瀏覽器中開啟:

    https://us-central1-MY_PROJECT.cloudfunctions.net/addMessage?text=uppercasemetoo
    

    函式會執行,並將瀏覽器重新導向至 資料庫位置的 Firebase 控制台 (儲存文字字串的位置)。這個 寫入事件會觸發「make upcase」函式,以便寫入大寫 字串版本。

部署及執行函式後 請在 Google Cloud 控制台中查看記錄檔。 需要刪除函式 請使用 Firebase CLI

在實際工作環境中,建議您最佳化函式效能和控管機制 設定要執行的執行個體數量上下限。詳情請見 控管資源調度行為 進一步瞭解這些執行階段選項

後續步驟

這份說明文件可協助您進一步瞭解如何 為 Cloud Functions 管理函式 以及如何 來處理 Cloud Functions 支援的所有事件類型。

如要進一步瞭解 Cloud Functions 也可以進行下列操作: