【问题标题】:What is the correct way to publish to GCP PubSub from a Cloud Function?从 Cloud Function 发布到 GCP PubSub 的正确方法是什么?
【发布时间】:2020-05-02 15:22:37
【问题描述】:

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

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

我正在使用来自here 的文档。 publish 被列为已弃用,并指向 publishMessage 作为其替代品。

我在使用 publishMessage 函数时收到的错误是“TypeError: Data must be in 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;
});

【问题讨论】:

    标签: javascript node.js google-cloud-firestore google-cloud-functions google-cloud-pubsub


    【解决方案1】:

    您链接到的 API 文档建议您提供 MessageOptions 对象作为第一个参数。根据该对象的 API 文档,您必须编写一个对象,其中包含用于指定有效负载的选项之一。如果你有一个节点缓冲区,你应该像这样组合对象:

    topic.publishMessage({data: otherBuffer}, callback);
    

    此方法是异步的,并返回一个 Promise 来指示消息何时发送。

    请记住,您需要从函数中返回一个承诺,该承诺只有在所有异步工作完成后才会解析。像现在这样返回 null 是行不通的。您应该使用 publishMessage() 返回的承诺告诉 Cloud Functions 您的工作已完成并且可以安全清理。

    return topic.publishMessage(...);
    

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

    【讨论】:

    • 这行得通,非常感谢您的快速响应!我只是想尽量减少可重现的代码 - 并尽可能多地保留文档中的示例。我知道使用承诺而不是回调函数(但使用它们仍然是新手)。实际上,当我将其作为回调保留时,它返回了一个不同的错误 - 错误:无法加载默认凭据。当我将其更改为返回承诺时,它会生成消息。
    猜你喜欢
    • 2020-11-24
    • 2019-07-03
    • 1970-01-01
    • 2022-01-05
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    相关资源
    最近更新 更多