Firebase Emulator Suite - simple pubsub example

Viewed 89

I have read MANY docs/blogs/SO articles on using the Firebase Emulator Suite trying a simple pubsub setup, but can't seem to get the Emulator to receive messages.

I have 2 functions in my functions/index.js:

const functions = require('firebase-functions');

const PROJECT_ID = 'my-example-pubsub-project';
const TOPIC_NAME = 'MY_TEST_TOPIC';

// receive messages to topic
export default functions.pubsub
  .topic(TOPIC_NAME)
  .onPublish((message, context) => {
    console.log(`got new message!!! ${JSON.stringify(message, null, 2)}`);
    return true;
  });

// publish message to topic
export default functions.https.onRequest(async (req, res) => {
  const { v1 } = require('@google-cloud/pubsub');
  const publisherClient = new v1.PublisherClient({
    projectId: process.env.GCLOUD_PROJECT,
  });
  const formattedTopic = publisherClient.projectTopicPath(PROJECT_ID, TOPIC_NAME);

  const data = JSON.stringify({ hello: 'world!' });

  // Publishes the message as JSON object
  const dataBuffer = Buffer.from(data);
  const messagesElement = {
    data: dataBuffer,
  };
  const messages = [messagesElement];

  // Build the request
  const request = {
    topic: formattedTopic,
    messages: messages,
  };

  return publisherClient
    .publish(request)
    .then(([responses]) => {
      console.log(`published(${responses.messageIds}) `);
      res.send(200);
    })
    .catch((ex) => {
      console.error(`ERROR: ${ex.message}`);
      res.send(555);
      throw ex; // be sure to fail the function
    });
});

When I run firebase emulators:start --only functions,firestore,pubsub and then run the HTTP method with wget -Sv -Ooutput.txt --method=GET http://localhost:5001/my-example-pubsub-project/us-central1/httpTestPublish, the HTTP function runs and I see its console output, but I can't seem to ever get the .onPublish() to run.

I notice that if I mess around with the values for v1.PublisherClient({projectId: PROJECT_ID}), then I will get a message showing up in the GCP cloud instance of the Subscription...but that's exactly what I don't want happening :)

0 Answers
Related