javascript - 从云功能发布到 GCP PubSub 的正确方法是什么?

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

当 Firestore 中的文档写入时,我尝试向 GCP PubSub 发布消息。

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

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

使用publishMessage函数时收到的错误是“TypeError:数据必须采用缓冲区的形式。”

知道我在 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 文档,您必须编写一个包含用于指定有效负载的选项之一的对象。如果你有一个 Node 缓冲区,你应该像这样组成对象:

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

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

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

return topic.publishMessage(...);

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

关于javascript - 从云功能发布到 GCP PubSub 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59758539/

相关文章:

mysql - 如何使 Sequelize 使用单数表名

firebase - 在 Flutter 中映射 Firestore 中的映射字段对象

firebase - Firebase Firestore REST API 是否支持流式传输

firebase - 如何在Dart的streambuilder中切换正在收听的流?

javascript - jqgrid userData 在刷新时发布 null

javascript - 多个 Promise 请求在 Javascript 中链接在一起

javascript - Node 是否在所需模块中运行所有代码?

node.js - 如何与 nx 并行运行 express 和 angular?

javascript - 如何访问 IE 中的节点类型常量

javascript - 空输入类型文件在 IE 中不起作用