Pub/Sub 觸發條件


Google Cloud 的 Pub/Sub 是遍及全球的訊息匯流排,可依您的需求自動進行擴充。您可以使用 functions.pubsub 建立處理 Pub/Sub 事件的函式。

觸發 pub/sub 函式

每當有新的 Pub/Sub 訊息傳送到特定主題時,都可以觸發函式。您必須指定要觸發函式的 Pub/Sub 主題名稱,並在 onPublish() 事件處理常式中設定事件:

exports.helloPubSub = functions.pubsub.topic('topic-name').onPublish((message) => {
  // ...
});

存取 Pub/Sub 訊息酬載 {:#access-pub/sub}

您可以透過傳回函式的 Message 物件存取 Pub/Sub 訊息的酬載。針對 Pub/Sub 訊息內文中含有 JSON 的訊息,Cloud Functions 適用的 Firebase SDK 提供可解碼訊息的輔助屬性。例如,下列訊息是以簡易 JSON 酬載發布:

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

您可以透過 json 屬性存取類似下方的 JSON 資料酬載:

  // Get the `name` attribute of the PubSub message JSON body.
  let name = null;
  try {
    name = message.json.name;
  } catch (e) {
    functions.logger.error('PubSub message was not JSON', e);
  }

其他非 JSON 酬載會以 Base64 編碼字串的形式包含在訊息物件中。如要讀取如下所示的訊息,您必須將 base64 編碼字串解碼,如下所示:

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

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

存取訊息屬性 {:#access-message}

Pub/Sub 訊息可搭配發布指令中設定的資料屬性一起傳送。舉例來說,您可以使用 name 屬性發布訊息:

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

您可以透過 Message.attributes 讀取這類屬性:

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

您可能會發現 Message.attributes 中未提供部分基本資料,例如訊息 ID 或訊息發布時間。如要解決這個問題,您可以在觸發事件的 EventContext 中存取這些詳細資料。例如:

exports.myFunction = functions.pubsub.topic('topic1').onPublish((message, context) => {
    console.log('The function was triggered at ', context.timestamp);
    console.log('The unique ID for the event is', context.eventId);
});