Pub/Sub トリガー


Google CloudPub/Sub は、グローバルに分散されたメッセージバスであり、必要に応じて自動的にスケーリングされます。新しい Pub/Sub メッセージが特定のトピックに送信されるたびに、関数をトリガーできます。

必要なモジュールをインポートする

まず、次の Pub/Sub イベントの処理に必要なモジュールをインポートします。

Node.jsPython
const {onMessagePublished} = require("firebase-functions/v2/pubsub");
const logger = require("firebase-functions/logger");
from firebase_functions import pubsub_fn

関数をトリガーする

関数をトリガーする Pub/Sub トピック名を指定し、イベント ハンドラ内でイベントを設定する必要があります。

Node.jsPython
exports.hellopubsub = onMessagePublished("topic-name", (event) => {
@pubsub_fn.on_message_published(topic="topic-name")
def hellopubsub(event: pubsub_fn.CloudEvent[pubsub_fn.MessagePublishedData]) -> None:
    """Log a message using data published to a Pub/Sub topic."""

Pub/Sub メッセージ ペイロードにアクセスする

Pub/Sub メッセージのペイロードには、関数に返されたメッセージ オブジェクトからアクセスできます。Pub/Sub メッセージ本文に JSON が含まれるメッセージの場合、Firebase SDK for Cloud Functions には、メッセージをデコードするためのヘルパー プロパティがあります。例として、単純な JSON ペイロードを持つパブリッシュされたメッセージを次に示します。

gcloud pubsub topics publish topic-name --message '{"name":"Xenia"}'

json プロパティを使用して、次のように JSON データ ペイロードにアクセスできます。

Node.jsPython
  // Get the `name` attribute of the PubSub message JSON body.
  let name = null;
  try {
    name = event.data.message.json.name;
  } catch (e) {
    logger.error("PubSub message was not JSON", e);
  }
# Get the `name` attribute of the PubSub message JSON body.
try:
    data = event.data.message.json
except ValueError:
    print("PubSub message was not JSON")
    return
if data is None:
    return
if "name" not in data:
    print("No 'name' key")
    return
name = data["name"]

その他の非 JSON ペイロードは、メッセージ オブジェクト内の base64 でエンコードされた文字列として Pub/Sub メッセージに含まれています。次のようなメッセージを読み込むには、次に示すように base64 でエンコードされた文字列をデコードする必要があります。

gcloud pubsub topics publish topic-name --message 'MyMessage'
Node.jsPython
// Decode the PubSub Message body.
const message = event.data.message;
const messageBody = message.data ?
      Buffer.from(message.data, "base64").toString() :
      null;
# Decode the PubSub message body.
message_body = base64.b64decode(event.data.message.data)

メッセージ属性にアクセスする

Pub/Sub メッセージは、publish コマンドでデータ属性を設定したうえで送信できます。例として、name 属性を設定したメッセージをパブリッシュしてみます。

gcloud pubsub topics publish topic-name --attribute name=Xenia

このような属性は、メッセージ オブジェクトの対応するプロパティから読み取ることができます。

Node.jsPython
// Get the `name` attribute of the message.
const name = event.data.message.attributes.name;
# Get the `name` attribute of the message.
if "name" not in event.data.message.attributes:
    print("No 'name' attribute")
    return
name = event.data.message.attributes["name"]