Search code examples
node.jsgoogle-cloud-platformgoogle-cloud-functionspublish-subscribegoogle-cloud-pubsub

How to access individual request param coming from GCP pubsub as a input to the cloud function node js?


I am writing a cloud function in node js, My requirement is that GCP pubsub topic will publish a json body as a message. This pubsub topic is a trigger point to my node js cloud function. It means whenever I publish a message from topic It should trigger my cloud function. This functionality is working as expected. But the issue comes where I am trying to access individual element of Json request data in my cloud function. If I log the data which is coming from pubsub in my cloud function, I am able to do that. My index.js

exports.helloPubSub = (data, context) => {
  const pubSubMessage = data;
  const messageData = pubSubMessage.data
    ? Buffer.from(pubSubMessage.data, 'base64').toString()
    : 'World';

  console.log(`message data is, ${messageData}!`);

};

Published pubsub message is :

{
    "companyName": "my-company",
    "companyLocation": "my-location"
}

When I am trying to access "companyName" in my cloud function from above published message I get log output as "company name is undefined". Below is the code I am trying:

exports.helloPubSub = (data, context) => {
  const pubSubMessage = data;
  const messageData = pubSubMessage.data
    ? Buffer.from(pubSubMessage.data, 'base64').toString()
    : 'World';

  console.log(`company name is, ${messageData.companyName}!`);

};

Note: I am referring https://cloud.google.com/functions/docs/tutorials/pubsub

Your helpful answers will be appreciated. Thank you !


Solution

  • You can't access the companyName because you try to access a property from a string.

    To access the data sent from PubSub you need to parse the decoded string using JSON.

    Try the following code:

     exports.helloPubSub = (event, context) => {
      const message = Buffer.from(event.data, 'base64').toString();
      const messageData = JSON.parse(message)
    
      console.log(`company name is, ${messageData.companyName}!`);
    
    };