[英]GCP Nodejs8 Cloud Function - Synchronous PubSub publish
[英]What is the correct way to publish to GCP PubSub from a Cloud Function?
在编写 Firestore 中的文档时,我正在尝试向 GCP PubSub 发布消息。
我已经让它工作了,但有一个被列为不推荐使用的功能。 当我尝试使用较新的函数时,出现错误。
我正在使用 这里的文档。 publish被列为已弃用,并指向publishMessage作为其替代品。
我在使用 publishMessage 函数时收到的错误是“TypeError: Data must be in the form of a Buffer”。
关于我在publishMessage语法中缺少什么的任何想法?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const firestore = admin.firestore();
const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub(MY_PROJECT);
exports.pubSubPublishTest = functions.firestore.document('pubSubTest/{docID}').onWrite((change, context) => {
const topic = pubsub.topic('test');
const otherBuffer = Buffer.from('this is the message');
const callback = (err, messageId) => {
if (err) {
console.error(`error encountered during publish - ${err}`);
} else {
console.log(`Message ${messageId} published.`);
}
};
// this worked, but the function is listed as deprecated
topic.publish(otherBuffer, callback);
// this did not work - {otherBuffer} is from the doc
// but I also tried without the curly braces and received the same error.
//topic.publishMessage({otherBuffer}, callback);
return null;
});
您链接到的 API 文档建议您提供MessageOptions对象作为第一个参数。 根据该对象的 API 文档,您必须编写一个包含用于指定有效负载的选项之一的对象。 如果你有一个节点缓冲区,你应该像这样组成对象:
topic.publishMessage({data: otherBuffer}, callback);
此方法是异步的,并返回一个承诺以指示何时发送消息。
还请记住,您需要从您的函数返回一个承诺,该承诺仅在所有异步工作完成后才能解决。 像现在这样返回 null 是行不通的。 您应该使用 publishMessage() 返回的承诺告诉 Cloud Functions 您的工作已完成并且可以安全清理。
return topic.publishMessage(...);
我建议还考虑使用该承诺而不是回调函数来继续其他工作(例如您的日志记录)。 学习如何有效地处理承诺对于在 Cloud Functions 环境中编写有效的 JavaScript 绝对至关重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.