Триггеры публикации/подписки

Google Cloud 's Pub/Sub is a globally distributed message bus that automatically scales as you need it. You can trigger a function whenever a new Pub/Sub message is sent to a specific topic.

Импортируйте необходимые модули.

To get started, import the modules required for handling Pub/Sub events:

Node.js

const {onMessagePublished} = require("firebase-functions/pubsub");
const logger = require("firebase-functions/logger");

Python

from firebase_functions import pubsub_fn

Запустите функцию

You must specify the Pub/Sub topic name that you want to trigger your function, and set the event within the event handler:

Node.js

exports.hellopubsub = onMessagePublished("topic-name", (event) => {

Python

@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 доступно из объекта сообщения, возвращаемого вашей функции. Для сообщений с JSON в теле сообщения Pub/Sub в Firebase SDK для Cloud Functions есть вспомогательное свойство для декодирования сообщения. Например, вот сообщение, опубликованное с простым содержимым в формате JSON:

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

You can access a JSON data payload like this via the json property:

Node.js

  // 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);
  }

Python

# 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, содержатся в сообщении Pub/Sub в виде строк, закодированных в base64, в объекте сообщения. Чтобы прочитать сообщение, подобное приведенному ниже, необходимо декодировать строку, закодированную в base64, как показано:

gcloud pubsub topics publish topic-name --message 'MyMessage'

Node.js

// Decode the PubSub Message body.
const message = event.data.message;
const messageBody = message.data ?
      Buffer.from(message.data, "base64").toString() :
      null;

Python

# Decode the PubSub message body.
message_body = base64.b64decode(event.data.message.data)

Доступ к атрибутам сообщения

Pub/Sub message can be sent with data attributes set in the publish command. For example, you could publish a message with a name attribute:

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

You can read such attributes from the corresponding property of the message object:

Node.js

// Get the `name` attribute of the message.
const name = event.data.message.attributes.name;

Python

# 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"]