Search code examples
google-cloud-platformgoogle-cloud-functionspublish-subscribegoogle-cloud-pubsub

Publish on a topic in an HTTP triggered function


I have written an HTTP triggered function in GCP and it computes some data as expected and after the computation, I would like to publish the result on a MQTT topic. I added the following snippet of code but it triggers an error:

Error: Error: Cannot find module '@google-cloud/pubsub'

Below is the code added

//decoding worked
const PubSub = require('@google-cloud/pubsub'); 
// Your Google Cloud Platform project ID
const projectId = 'XXXXX';

// Instantiates a client
const pubsubClient = new PubSub({
  projectId: projectId
});

// The name for the new topic
const topicName = 'XXXX';

// Creates the new topic
pubsubClient
  .createTopic(topicName)
  .then(results => {
    const topic = results[0];
    console.log(`Topic ${topic.name} created.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

If I get rid of the import of library, I get

 Error: ReferenceError: PubSub is not defined

So - How can I publish in a topic from an HTTP triggered function in gcp?


Solution

  • You need to install the @google-cloud/pubsub library as dependency so that your Cloud Function can import it successfully. You can do it by running the following command locally:

    npm install --save @google-cloud/pubsub
    

    This will include this library in the package.json file you upload with your function code.

    If you are writing your function from the Developer Console directly, you'll need to add the following to your package.json file:

    "dependencies": {
        "@google-cloud/pubsub": "^0.19.0"
    }