This guide is an example of how to develop a function to receive PubSub messages in Typescript with the Functions Framework.
-
Use gts to configure Typescript.
npx gts init
-
Install the required packages:
npm install @google-cloud/functions-framework npm install @google-cloud/pubsub npm install concurrently nodemon --save-dev
-
Replace the contents of
src/index.ts
with:import {Context, EventFunction} from "@google-cloud/functions-framework/build/src/functions"; import {PubsubMessage} from "@google-cloud/pubsub/build/src/publisher"; export const helloPubSub: EventFunction = (message: PubsubMessage, context: Context) => { const data = message.data ? Buffer.from(message.data as string, "base64").toString() : "No Message"; console.log(data); };
-
Compile your Typescript code:
npm run compile
This should compile your
index.ts
tobuild/src/index.js
.
-
Adjust
main
field inpackage.json
to point to the compiled javascript source."main": "build/src/index.js", ...
-
Remove
prepare
script inpackage.json
created by gts. This is because theprepare
script requires typescript to be installed and will cause the function to fail to deploy if not removed. -
Create a Pub/Sub topic, where
COOL_TOPIC
is the name of the new topic you are creating:gcloud pubsub topics create COOL_TOPIC
-
Deploy:
gcloud functions deploy helloPubSub \ --runtime nodejs16 \ --trigger-topic COOL_TOPIC
-
Publish a message to the topic to test your function:
gcloud pubsub topics publish COOL_TOPIC --message="hello"