Skip to content

Commit 759aac1

Browse files
diogosantosgrant
andauthored
docs: added PubSub Typescript doc (#462)
Co-authored-by: Grant Timmerman <[email protected]>
1 parent 588fbd0 commit 759aac1

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

docs/typescript-pubsub.md

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# PubSub Event Function in Typescript
2+
3+
This guide is an example of how to develop a function to receive PubSub messages in Typescript with the Functions Framework.
4+
5+
1. Use [gts](https://github.com/google/gts) to configure Typescript.
6+
7+
```sh
8+
npx gts init
9+
```
10+
11+
2. Install the required packages:
12+
13+
```sh
14+
npm install @google-cloud/functions-framework
15+
npm install @google-cloud/pubsub
16+
npm install concurrently nodemon --save-dev
17+
```
18+
19+
3. Replace the contents of `src/index.ts` with:
20+
21+
```ts
22+
import {Context, EventFunction} from "@google-cloud/functions-framework/build/src/functions";
23+
import {PubsubMessage} from "@google-cloud/pubsub/build/src/publisher";
24+
25+
export const helloPubSub: EventFunction = (message: PubsubMessage, context: Context) => {
26+
const data = message.data ? Buffer.from(message.data as string, "base64").toString() : "No Message";
27+
console.log(data);
28+
};
29+
```
30+
31+
4. Compile your Typescript code:
32+
33+
```sh
34+
npm run compile
35+
```
36+
37+
This should compile your `index.ts` to `build/src/index.js`.
38+
39+
## Deploying with gcloud CLI
40+
41+
1. Adjust `main` field in `package.json` to point to the compiled javascript source.
42+
43+
```js
44+
"main": "build/src/index.js",
45+
...
46+
```
47+
48+
2. Remove `prepare` script in `package.json` created by [gts](https://github.com/google/gts). This is because the `prepare` script requires typescript to be installed and will
49+
cause the function to fail to deploy if not removed.
50+
51+
3. Create a Pub/Sub topic, where `COOL_TOPIC` is the name of the new topic you are creating:
52+
53+
```sh
54+
gcloud pubsub topics create COOL_TOPIC
55+
```
56+
57+
4. Deploy:
58+
59+
```sh
60+
gcloud functions deploy helloPubSub \
61+
--runtime nodejs16 \
62+
--trigger-topic COOL_TOPIC
63+
```
64+
65+
5. Publish a message to the topic to test your function:
66+
67+
```sh
68+
gcloud pubsub topics publish COOL_TOPIC --message="hello"
69+
```
70+

0 commit comments

Comments
 (0)