从 Cloud Functions 发布到 GCP PubSub 的正确方法是什么?

What is the correct way to publish to GCP PubSub from a Cloud Function?

我正在尝试在 Firestore 中编写文档时向 GCP PubSub 发布消息。

我已经让它工作了,但是有一个功能被列为已弃用。当我尝试使用较新的函数时出现错误。

我正在使用 here 中的文档。 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);

此方法是异步的,并且return承诺在发送消息时指示。

还请记住,您需要 return 来自您的函数的承诺,该承诺仅在所有异步工作完成后才解析。像现在这样返回 null 是行不通的。您应该使用由 publishMessage() 编辑的承诺 return 告诉 Cloud Functions 您的工作已完成并且可以安全清理了。

return topic.publishMessage(...);

我还建议考虑使用该承诺而不是回调函数来继续其他工作(例如您的日志记录)。 Learning how to deal with promises effectively 对于在 Cloud Functions 环境中编写有效的 JavaScript 绝对至关重要。