Deploy GCP Cloud Function with Event Trigger via PubSub

2023/04/062 min read
bookmark this
Responsive image

Create Index.js Entry Point file

Create Index.js file andd add below code, it'll get the dependency package from '@google-cloud/functions-framework', create the endpoint with cloudEvent, and log all the request event variable to the log so we can verify later on.

const functions = require('@google-cloud/functions-framework');

functions.cloudEvent('myEvent', event => {

    console.info('test_data', event);

});

Include dependency package @google-cloud/functions-framework for GCP Cloud Function

Since we'll use the package for GCP HTTP Cloud Function, so we need to add this dependency package at package.json file.

"dependencies": {
    "@google-cloud/functions-framework": "^3.3.0"
}

Deploy to GCP Cloud

Create Pub/Sub Topic

Before deploy the Node.js cloud to GCP cloud, we'll need to create pub/sub topic. We'll use below command to create topic as my_topic.

gcloud pubsub topics create my_topic

Deploy Cloud Function via local environment

Below is the code for deploy Node.js code to GCP Cloud, run this at the same source code directory, make sure entry-point is the name written in the index.js and trigger-topic is the one we just create, my_topic.

gcloud functions deploy myEventTriggerFunction --gen2 --region=us-central1 --runtime=nodejs18 --entry-point=myEvent --trigger-topic=my_topic --allow-unauthenticated

Send Pub/Sub Message

After verify cloud function deploy successfully at local environment, we can publish message and verify the logs at cloud later. Run below command at local to send test message to our topic.

gcloud pubsub topics publish my_topic --message="my first message"

Verify the logs

Now, if everything works as expected, we should see the logs at Cloud Function log tab, the below data field should store the actual message we send earlier and encoded with base64, to read the message either you can either use online tools to decode the text back from base64 or in the actual application you can decode the message.data for additional process. Test Cloud Function Event Trigger Logs

Trigger Event with Cloud Scheduler

We have setup the Node.js App trigger with GCP Pub/Sub, so we can also use the Cloud Scheduler to run the Node.js app regularly. The blow command will setup the GCP Cloud Scheduler run every minutes and send message as from_scheduler. This design can help in case if you have any regular process need to run in a Schedule fashion, run as every minutes or every hour or maybe once a day.

gcloud scheduler jobs create pubsub my_job --location=us-central1 --schedule="* * * * *" --topic="my_topic" --message-body="from_scheduler"