[英]Cloud Function (trigger by HTTP) that would publish a message to PubSub
I am trying to create HTTP API in Cloud Function - that eventually published a message t PubSub.我正在尝试在 Cloud Function 中创建 HTTP API - 最终发布了一条消息 t PubSub。 Understood, that there is PubSub REST API - but it enforced me to set up the authentication (in client side) - that I would like to skip and move it to the server side.明白了,有 PubSub REST API - 但它强制我设置身份验证(在客户端) - 我想跳过并将其移动到服务器端。
Below code is deployed as Google Cloud Function with this command gcloud functions deploy helloGET --runtime nodejs8 --trigger-http
下面的代码被部署为谷歌云函数,使用这个命令gcloud functions deploy helloGET --runtime nodejs8 --trigger-http
But while tested in browser, it is errored out Error: could not handle the request
Any suggestion is appreciated, thanks!但是在浏览器中测试时,它出错了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);
})
);
};
Below code will work.下面的代码将起作用。 But it will take around 30 seconds or plus for the subscriber to receive the event - it is way too slow for my used case :S但是订阅者需要大约 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.