简体   繁体   中英

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. But, I would like receive a http request and send a pub message. 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.

You can easily use the Node.js Pub/Sub client library , with already defined functionalities, like publish .

Or, if you prefer, you can build your own client , directly calling the REST API for Google Cloud Pub/Sub . There's also a RPC reference if it suits your needs better.


You won't need

information like host, port, id, passwd of broker

as the mentioned client, or your REST API requests will require authentication .

You need to import pub-sub library const {PubSub} = require('@google-cloud/pubsub') , initiate client, and publish messages.
Docs:


However, One more way is to trigger background function on firestore writes .

whenever you create a doc in a collection ( pubsub ), your bg function will get invoked on the doc write:

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

Also, it's just not limited to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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