简体   繁体   中英

How to use Google PubSub without Cloud Function

How can I use Google PubSub to retrieve billing updates without using cloud functions? I am using the code below currently but it says that onPublish does not exist:

const { PubSub } = require('@google-cloud/pubsub');
const pubsub = new PubSub('MyProjectID');



handleServerEvent = pubsub.topic(GOOGLE_PLAY_PUBSUB_BILLING_TOPIC)
  .onPublish(async (message) => {

  })

TypeError: pubsub.topic(...).onPublish is not a function

I am using Node.js and want to react to events published on a topic.

The onPublish() method is a part of Cloud Functions API. You need to use createSubscription() to get a Subscription object and then use it to listen for new messages. Try the following:

const listenToTopic = async (topicName: string) => {
  const [sub] = await pubsub
    .topic(topicName)
    .createSubscription("subscriptionName");

  sub.on("message", (message) => {
    message.ack();
    console.log(`Received message: ${message}`);  
  });
};

// start listener
listenToTopic(GOOGLE_PLAY_PUBSUB_BILLING_TOPIC)

After creating the subscription once you need to change createSubscription("subscriptionName") to subscription("subscriptionName") to listen to incoming messages as the subscription has been created already

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM