【问题标题】:How to publish message in Google Pub/Sub from Firebase Cloud Function?如何从 Firebase Cloud Function 在 Google Pub/Sub 中发布消息?
【发布时间】:2018-06-22 18:35:54
【问题描述】:

我写了一个函数来接收一个 http 请求并发送一封电子邮件。但是,我想收到一个 http 请求并发送一个 pub 消息。问题是文档不清楚。我该怎么做?

这是我的实际代码。

exports.weeklyEmail = functions.https.onRequest((req,res) => {
const email = '****@gmail.com'

console.log('Sending e-mail')

const mailOptions = {
    to: email,
    from: '****@alunos.utfpr.edu.br',
    subject: 'Teste',
    text: 'Conteudo do email '
}   

mailTransport.sendMail(mailOptions).then(
    () => {         
        res.send('Email sent')
    }
).catch(error => {
    res.send(error)
})
})

【问题讨论】:

    标签: javascript publish-subscribe google-cloud-functions google-cloud-pubsub


    【解决方案1】:

    需要导入pub-sub库const {PubSub} = require('@google-cloud/pubsub'),发起客户端,发布消息。
    文档:


    不过,另一种方法是在firestore writes 上触发后台功能。

    每当您在集合 (pubsub) 中创建文档时,您的 bg 函数都会在文档写入时被调用:

    exports.myTriggerFunction = functions.firestore
      .document('pubsub/{docId}')
      .onWrite((change, context) => { /* ... */ });
    

    而且,它不仅限于onCreate

    Event Type  Trigger
    onCreate    Triggered when a document is written to for the first time.
    onUpdate    Triggered when a document already exists and has any value changed.
    onDelete    Triggered when a document with data is deleted.
    onWrite     Triggered when onCreate, onUpdate or onDelete is triggered.
    

    【讨论】:

      【解决方案2】:

      据我了解,您希望通过 Firebase Cloud Functions 实现向 Pub/Sub 发送消息。

      您可以轻松地使用Node.js Pub/Sub client library,它具有已定义的功能,例如publish

      或者,如果您愿意,您可以构建自己的客户端,直接调用REST API for Google Cloud Pub/Sub。如果它更适合您的需求,还有一个 RPC reference


      你不需要

      broker 的主机、端口、id、密码等信息

      作为提到的客户端,否则您的 REST API 请求将需要 authentication

      【讨论】:

      • 你知道我是否可以在没有 Apple Push Notifications Service 的情况下在 iOS 应用中使用它吗?
      • 很遗憾,我不知道 Apple 推送通知服务。鉴于 Google 的 Pub/Sub 可以通过 APIs Services 实现,它应该独立于平台、编程语言......即只要可以实现 HTTP 客户端来执行对 REST API 端点的请求。我不知道它是否相关,或者一个很好的类比,但Firebase Cloud Messaging 也适用于 iOS ......所以它可能与 Cloud Pub/Sub 相同
      • 您的评论可能值得一个新的 SO 帖子,因为它将处理一个特别不同的主题。从“如何通过 Firebase Cloud Function 在 Pub/Sub 中发布”到“如何将 Apple Push Notifications Service 与 .... 集成”(猜测)
      • 谈到身份验证 - 在 Fireabse 云函数中使用 Pub/Sub 客户端库时如何对其进行身份验证?我尝试创建一个简单的函数,但在函数尝试发布消息时收到PERMISSION_DENIED 错误。