How do I send the event changes of a collection to pub/sub?

this is the code i am using:

  exports = function(changeEvent) {
  
    const { PubSub } = require('@google-cloud/pubsub');
    const atob = require('JSON');
     
    // Set up Google Cloud Pub/Sub credentials
    const projectId = 'xxxxs';
    const topicName = 'xxxx8';
    const keyFilename = context.values.get('GOOGLE_APPLICATION_CREDENTIALS');
    // Create a Pub/Sub client with credentials
    const pubsub = new PubSub({ projectId, keyFilename });
    
    // Publish a message to the Pub/Sub topic
    try {
      const message = JSON.stringify(changeEvent.fullDocument);
      const dataBuffer = Buffer.from(message);
      const topic = pubsub.topic(topicName);
      return topic.publish(dataBuffer)
        .then((messageId) => console.log(`Message ${messageId} published.`))
        .catch((err) => console.error(`Error publishing message: ${err}`));
    } catch (err) {
      console.error(`Error converting changeEvent to JSON: ${err}`);
    }
  };

Error:
Error publishing message: FunctionError: TypeError: The “path” argument must be of type string. Received type object

Maybe return topic.publish(dataBuffer.toString())

thanks for your answer, now it gives me another error when it does the const keyFilename = JSON.parse(context.values.get('GOOGLE_APPLICATION_CREDENTIALS')); gives the following error:

Mistake:
SyntaxError: invalid character ‘o’ looking for beginning of value
exports = function(changeEvent) {

new code:

    const { PubSub } = require('@google-cloud/pubsub');
    const atob = require('JSON');
     
    // Set up Google Cloud Pub/Sub credentials
    const projectId = 'xxx';
    const topicName = 'xxxxx';
    const keyFilename = JSON.parse(context.values.get('GOOGLE_APPLICATION_CREDENTIALS'));
    // Create a Pub/Sub client with credentials
    const pubsub = new PubSub({ projectId, keyFilename });
    
    // Publish a message to the Pub/Sub topic
    try {
      const message = JSON.stringify(changeEvent.fullDocument);
      const dataBuffer = Buffer.from(message);
      const topic = pubsub.topic(topicName);
      return topic.publish(dataBuffer.toString())
        .then((messageId) => console.log(`Message ${messageId} published.`))
        .catch((err) => console.error(`Error publishing message: ${err}`));
    } catch (err) {
      console.error(`Error converting changeEvent to JSON: ${err}`);
    }
  };

Do you know what is the way to connect to pubsub?

Thanks

I’ve found it very difficult. I use Apache Camel.