Is it possible to trigger cloudEvent with pubsub

104 Views Asked by At

Is it possible to trigger cloud event from pubsub.

import { cloudEvent } from "@google-cloud/functions-framework"

export const myCloudEvent = cloudEvent<GoogleDrivePageMessage>("myTopic", cloudEvent => {
  const data = cloudEvent.data;
  logger.log("Called pub sub")
});

and trigger it by calling publishMessage

const pubsub = new PubSub(config);
const topic = pubsub.topic("myTopic");
topic.publishMessage({ data: Buffer.from(messageJson) }, (error, messageId) => {
      if (error) {
        logger.log(`There was an error trying to send pubsub message: ${messageId}`, error)
      }
    });

Also i am trying to test this locally but the emulator doesn't seem to even load cloudEvent function. How would i test this locally without deploying first.

2

There are 2 best solutions below

0
Dživo Jelić On BEST ANSWER

I used onMessagePublished to be able to handle the message

import { onMessagePublished } from "firebase-functions/v2/pubsub";

export const handleMessage = onMessagePublished<MyMessage>("MYTOPIC", async (event) => {})

So it is possible but no with a cloud event i still dont understand the difference.

Also i would like to add that documentation is not good and there is no support for local development so avoid firebase if you want to build something serious

1
guillaume blaquiere On

PubSub does not support CloudEvent format natively (it's close but not similar). When you read data from pubSub, the library translate the PubSub format in Cloud Event format.

However, to publish messages, you must publish them in PubSub format (attribute and payload, instead of headers and body)