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