Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use firebase emulators pubsub to test timed functions locally?

Tags:

I'm using firebase for a project and am working on creating a schedule function using the following code. I want to log a message every minute this runs.

export const timedQuery = functions.pubsub.schedule('1 * * * *').onRun((context) => { console.log("I am running") return null; }) 

I have the main logic of the code working under an http function and would like to see if this works locally before deploying to production. Going through firebase docs I've downloaded all of the firebase emulators and use "firebase emulators:start" to get them running. From the logs it looks like my pubsub emulator starts successfully at localhost:8085 and pubsub function is initialized however even after waiting for 2 - 3 minutes nothing prints out. Is it possible to test scheduled functions locally?

Also I created this without using google cloud scheduler since I'm only on firebase.

like image 371
zeke13210 Avatar asked Apr 16 '20 15:04

zeke13210


People also ask

How do I use firebase Pubsub emulator?

To use Pubsub in Firebase Functions we must first install the pubsub node client. To do so, run npm i @google-cloud/pubsub in the terminal. Now we got an HTTP endpoint we can call that will post a message to the pubsub emulator. This code is just the bare bones and not too useful.


1 Answers

Actually there is a Firebase PubSub emulator. To enable it you need to have the recent CLI installed (it's in 8.2.0 for sure)

  • Rerun Firebase Init
  • Select Emulators (spacebar)
  • Select PubSub (and others you wish)
  • Configure your desired dev ports
  • Have the CLI install the emulators

Create a test script locally to submit PubSub messages into the queue:

const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase);  const { PubSub } = require('@google-cloud/pubsub'); const pubsub = new PubSub();  exports.pubsubWriter = functions.https.onRequest(async (req, res) => {     console.log("Pubsub Emulator:", process.env.PUBSUB_EMULATOR_HOST);      const msg = await pubsub.topic('test-topic').publishJSON({         foo: 'bar',         date: new Date()     }, { attr1: 'value' });      res.json({         published: msg     }) }); 
like image 90
Arno Zwaag Avatar answered Sep 19 '22 15:09

Arno Zwaag