2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GCP Pub/SubのメッセージはCloud Functionsへどう届くか

Last updated at Posted at 2019-12-05

概要

GCP Pub/SubをTriggerにしたCloud Functionは、メッセージをどう受け取るのか調べてみました。

実験

試しに次のようにメッセージをPublishしてみます。


Screen Shot 2562-12-05 at 17.47.27.png

すると、次のようになりました。
attributesにメッセージ属性が入り、dataにメッセージ本文が入ってくるようです。

exports.test = (pubSubEvent, context) => {
  console.log(pubSubEvent)
};

// -> {"@type":"type.googleapis.com/google.pubsub.v1.PubsubMessage","attributes":{"key":"value"},"data":"bWVzc2FnZQ=="}

しかしメッセージ本文はbase64で格納されているため、使える形にするにはデコードする必要があります。

The payload of the PubsubMessage object, the data published to the topic, is stored as a base64-encoded string in the data attribute of the PubsubMessage. To extract the payload of the PubsubMessage object, you may need to decode the data attribute as shown in the examples below.

ref) https://cloud.google.com/functions/docs/calling/pubsub#event_structure

exports.test = (pubSubEvent, context, callback) => {
  console.log(Buffer.from(pubSubEvent.data, 'base64').toString())
};

// -> message

Cloud Schedulerの場合

Cloud SchedulerでPub/SubをPublishするとき、payloadを指定できます。
Screen Shot 2562-12-05 at 18.50.09.png


このpayloadは、dataの中に入ってくるようです。
attributesを指定するには、gcloudコマンド経由でジョブを作成すると良いようです。

ref) Cloud Schedulerのジョブにattributesを設定する

Context

ちなみにcontextの中身は、こちらに記載されていました。
TypeScriptで書くとこんな感じ

type Context = {
    eventId: string,
    timestamp: string,
    eventType: string,
    resource: string
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?