Cloud Functions triggered by Pub/Sub

The most common way to trigger a Cloud Function is with an HTTP request, as seen previously. In contrast, background functions are used to invoke Cloud Functions indirectly through a message, a Pub/Sub topic, or an object change notification from a Google Cloud Storage bucket. Such cloud functions take in an event as a parameter and, optionally, a callback as another. The event parameter has various properties that we can make use of within our function:

Now, we will invoke cloud functions via pub/sub notifications (event or object change)

  1. Write the Cloud Function and save it as index.js (it will be stored under the VM of the Cloud Shell you have been provided with):
/**
* Background Cloud Function to be triggered by Pub/Sub.
*/
exports.helloPubSub = function (event, callback)
{
const pubsubMessage = event.data;
const name = pubsubMessage.data ? Buffer.from(pubsubMessage.data, 'base64').toString() : 'World';

console.log(`Hello, ${name}!`);

callback();
};
  1. To deploy the function, the gcloud beta functions deploy command can be used:
gcloud beta functions deploy helloPubSub --trigger-topic hello_world  
  1. Invoke (trigger) the Cloud Function.
  2. Now, the deployed function can be called directly, or by publishing a message to the trigger topic. To test the direct invocation, use the following command:
gcloud beta functions call helloPubSub --data '{"data":"dGVzdCB1c2Vy"}'

Here, test user is encoded in base64, thus you can see dGVzdCB1c2Vy. As a result, the function logs should show Hello test user!.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset