טריגרים של Pub/Sub

Google Cloud's Pub/Sub הוא אוטובוס הודעות מבוזר גלובלית שניתן להרחבה אוטומטית לפי הצורך. אפשר להפעיל פונקציה בכל פעם שנשלחת הודעה חדשה Pub/Sub לנושא ספציפי.

ייבוא המודולים הנדרשים

כדי להתחיל, מייבאים את המודולים שנדרשים לטיפול באירועים של Pub/Sub:

Node.js

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

Python

from firebase_functions import pubsub_fn

הפעלת הפונקציה

צריך לציין את Pub/Sub שם הנושא שרוצים להפעיל את הפונקציה שלו, ולהגדיר את האירוע בתוך 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."""

גישה למטען הייעודי (payload) של הודעת Pub/Sub

המטען הייעודי (payload) של ההודעה Pub/Sub נגיש מאובייקט ההודעה שמוחזר לפונקציה. בהודעות עם JSON בגוף ההודעה Pub/Sub, ל-SDK של Firebase ל-Cloud Functions יש מאפיין עזר לפענוח ההודעה. לדוגמה, הנה הודעה שפורסמה עם מטען ייעודי (payload) פשוט של JSON:

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

אפשר לגשת למטען ייעודי (payload) של נתוני JSON כמו זה באמצעות המאפיין json:

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

מטענים ייעודיים (payload) אחרים שאינם 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 עם מאפייני נתונים שמוגדרים בפקודה publish. לדוגמה, אפשר לפרסם הודעה עם מאפיין name:

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

אפשר לקרוא את המאפיינים האלה מהמאפיין המתאים של אובייקט ההודעה:

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