[英]Cloud Function (trigger by HTTP) that would publish a message to PubSub
我正在嘗試在 Cloud Function 中創建 HTTP API - 最終發布了一條消息 t PubSub。 明白了,有 PubSub REST API - 但它強制我設置身份驗證(在客戶端) - 我想跳過並將其移動到服務器端。
下面的代碼被部署為谷歌雲函數,使用這個命令gcloud functions deploy helloGET --runtime nodejs8 --trigger-http
但是在瀏覽器中測試時,它出錯了Error: could not handle the request
任何建議表示贊賞,謝謝!
"use strict";
// [START functions_pubsub_setup]
const { PubSub } = require("@google-cloud/pubsub");
// Instantiates a client
const pubsub = new PubSub();
// [END functions_pubsub_setup]
const Buffer = require("safe-buffer").Buffer;
exports.helloGET = (req, res) => {
const topic = pubsub.topic("projects/myproject/topics/openit");
const message = {
data: {
message: "req.body.message"
}
};
// Publishes a message
res.send(
topic
.publish(message)
.then(() => res.status(200).send("Message published."))
.catch(err => {
err = `Catch block ... ${err}`;
console.error(err);
res.status(500).send(err);
return Promise.reject(err);
})
);
};
下面的代碼將起作用。 但是訂閱者需要大約 30 秒或更長時間才能接收到事件 - 對於我的用例來說太慢了:S
"use strict";
const { PubSub } = require("@google-cloud/pubsub");
const pubsub = new PubSub();
const Buffer = require("safe-buffer").Buffer;
exports.helloGET = async (req, res) => {
var toPublish = `hello ${Date.now()}`;
publishMessage("_REPLACE_WITH_TOPIC_NAME_", toPublish);
res.send(`Published ${toPublish}`);
};
async function publishMessage(topicName, data) {
console.log("=> publishMessage, data = ", data);
const dataBuffer = Buffer.from(data);
const topic = pubsub.topic(topicName);
const publisher = topic.publisher();
publisher.publish(dataBuffer, { a: "XYZ" }, function() {
console.log("Published eventually ...");
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.