💥 Test Pub/Sub with the Functions Framework and Pub/Sub Emulator 🔧
EDIT: This article may contain technical issues. Read with a grain of salt.
Google Cloud Functions come in 2 flavors: HTTP & background functions.
You use background functions when you want to have your Cloud Function invoked indirectly in response to an event, such as:
- ✉️ A message on a Pub/Sub topic
- 📦 A change in a Cloud Storage bucket
- 🔥 A Firebase event
In this blogpost, we’ll talk about Pub/Sub and teach you how you can test your code using the Node Function Framework and Pub/Sub Emulator.
But before we begin, let’s level set.
What is Cloud Pub/Sub and Pub/Sub triggers?
Cloud Pub/Sub is a fully-managed scalable event ingestion and delivery system for asynchronous independent serverless applications. It’s the backbone for communication between many event-driven programs.
With the Cloud Pub/Sub Emulator, you can emulate a production environment on your computer. Read more in the docs.
With Google Cloud Functions, you can easily trigger your code to run on a new event with the Cloud Pub/Sub trigger.
Together, you can more easily build decoupled systems. Let’s try using Cloud Pub/Sub and Cloud Functions together…
Create a Google Cloud Function with a Cloud Pub/Sub Trigger
Create a Cloud Function
Let’s create a Cloud Function with a Cloud Pub/Sub trigger. Create an index.js
file like this:
Create a helper npm script:
{
"scripts": {
"start": "npx @google-cloud/functions-framework --target=helloPubSub --signature-type=event"
}
}
Now when you run npm run start
, you’ll see your Cloud Function running locally. Even though the function is running at localhost
, we’re listening to Events, not raw HTTP requests.
Pub/Sub Emulator
To develop and test your application locally, you can use the Cloud Pub/Sub emulator, which provides local emulation of the production Cloud Pub/Sub environment.
Prepare your Pub/Sub Emulator
Create a new file mockPubsub.json
with the following contents:
Then in a terminal session, start the emulator:
gcloud beta emulators pubsub start
Test your Function
To send an individual Cloud Pub/Sub message, use cURL
:
In your terminal running the Functions Framework, you’ll see a log message from your Node app with the contents of your Cloud Pub/Sub event:
There you have it! You’ve now tested your Cloud Pub/Sub Function locally.
When you’re ready to test in production, use gcloud
with a script similar to below:
gcloud pubsub topics create MY_TOPIC # Create a Pub/Sub topic
gcloud functions deploy MY_FUNCTION \
--trigger-topic MY_TOPIC \
--runtime nodejs10 # Deploy a Function with a Pub/Sub trigger
gcloud pubsub topics publish MY_TOPIC --message '{ "greeting": "Hello" }'
Thanks for Reading!
Learn more about these technologies in the following pages: