1
votes

I am trying to create HTTP API in Cloud Function - that eventually published a message t PubSub. Understood, that there is PubSub REST API - but it enforced me to set up the authentication (in client side) - that I would like to skip and move it to the server side.

Below code is deployed as Google Cloud Function with this command gcloud functions deploy helloGET --runtime nodejs8 --trigger-http

But while tested in browser, it is errored out Error: could not handle the request Any suggestion is appreciated, thanks!

"use strict";

// [START functions_pubsub_setup]
const { PubSub } = require("@google-cloud/pubsub");

// Instantiates a client
const pubsub = new PubSub();
// [END functions_pubsub_setup]

const Buffer = require("safe-buffer").Buffer;

exports.helloGET = (req, res) => {
  const topic = pubsub.topic("projects/myproject/topics/openit");

  const message = {
    data: {
      message: "req.body.message"
    }
  };

  // Publishes a message
  res.send(
    topic
      .publish(message)
      .then(() => res.status(200).send("Message published."))
      .catch(err => {
        err = `Catch block  ... ${err}`;
        console.error(err);
        res.status(500).send(err);
        return Promise.reject(err);
      })
  );
};
1

1 Answers

1
votes

Below code will work. But it will take around 30 seconds or plus for the subscriber to receive the event - it is way too slow for my used case :S

"use strict";
const { PubSub } = require("@google-cloud/pubsub");
const pubsub = new PubSub();
const Buffer = require("safe-buffer").Buffer;

exports.helloGET = async (req, res) => {
  var toPublish = `hello ${Date.now()}`;
  publishMessage("_REPLACE_WITH_TOPIC_NAME_", toPublish);
  res.send(`Published ${toPublish}`);
};

async function publishMessage(topicName, data) {
  console.log("=> publishMessage, data = ", data);
  const dataBuffer = Buffer.from(data);
  const topic = pubsub.topic(topicName);
  const publisher = topic.publisher();
  publisher.publish(dataBuffer, { a: "XYZ" }, function() {
    console.log("Published eventually ...");
  });
}