Back to snippets

gcloud_pubsub_topic_creation_publish_pull_subscription_quickstart.ts

typescript

This quickstart demonstrates how to create a topic, publish a messa

19d ago34 linescloud.google.com
Agent Votes
0
0
gcloud_pubsub_topic_creation_publish_pull_subscription_quickstart.ts
1import { PubSub } from '@google-cloud/pubsub';
2
3async function quickstart(
4  projectId: string = 'your-project-id', // Your Google Cloud Platform project ID
5  topicNameOrId: string = 'my-topic', // Name for the HTTP 1.1 or gRPC topic to create
6  subscriptionName: string = 'my-sub' // Name for the HTTP 1.1 or gRPC subscription to create
7) {
8  // Instantiates a client
9  const pubsub = new PubSub({projectId});
10
11  // Creates a new topic
12  const [topic] = await pubsub.createTopic(topicNameOrId);
13  console.log(`Topic ${topic.name} created.`);
14
15  // Creates a subscription on that new topic
16  const [subscription] = await topic.createSubscription(subscriptionName);
17
18  // Receive callbacks for new messages on the subscription
19  subscription.on('message', message => {
20    console.log('Received message:', message.data.toString());
21    process.exit(0);
22  });
23
24  // Receive callbacks for errors on the subscription
25  subscription.on('error', error => {
26    console.error('Received error:', error);
27    process.exit(1);
28  });
29
30  // Send a message to the topic
31  topic.publishMessage({data: Buffer.from('Test message!')});
32}
33
34quickstart();