简体   繁体   English

如何从 Firebase Cloud Function 在 Google Pub/Sub 中发布消息?

[英]How to publish message in Google Pub/Sub from Firebase Cloud Function?

I wrote a function that receive a http request and send a e-mail.我写了一个 function 接收 http 请求并发送电子邮件。 But, I would like receive a http request and send a pub message.但是,我想收到一个 http 请求并发送一条发布消息。 The problem is that the documentation is not clear.问题是文档不清楚。 How I do that?我该怎么做?

This is my actual code.这是我的实际代码。

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)
})
})

As I understand, you wish to send a message to Pub/Sub from your Firebase Cloud Functions implementation. 据我了解,您希望从Firebase云功能实施中向Pub / Sub发送消息。

You can easily use the Node.js Pub/Sub client library , with already defined functionalities, like publish . 您可以轻松使用Node.js Pub / Sub客户端库 ,它具有已定义的功能,例如发布

Or, if you prefer, you can build your own client , directly calling the REST API for Google Cloud Pub/Sub . 或者,如果您愿意,可以构建自己的客户端 ,直接调用Google Cloud Pub / SubREST API There's also a RPC reference if it suits your needs better. 如果它更适合您的需求,还有一个RPC引用


You won't need 你不需要

information like host, port, id, passwd of broker 代理的主机,端口,id,passwd等信息

as the mentioned client, or your REST API requests will require authentication . 作为提到的客户端,或者您的REST API请求将需要身份验证

You need to import pub-sub library const {PubSub} = require('@google-cloud/pubsub') , initiate client, and publish messages.您需要导入 pub-sub 库const {PubSub} = require('@google-cloud/pubsub') ,启动客户端并发布消息。
Docs:文档:


However, One more way is to trigger background function on firestore writes .但是,另一种方法是在firestore 写入时触发背景 function。

whenever you create a doc in a collection ( pubsub ), your bg function will get invoked on the doc write:每当您在集合 ( pubsub ) 中创建文档时,您的 bg function 将在文档写入时被调用:

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

Also, it's just not limited to onCreate :此外,它不仅限于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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM