5

I'm using gcloud-node.

createTopic api returns error 409, if that topic exist already. Is there a flag that can implicitly create a topic when publishing a message or Is there an API to check if a topic exist already?

Its easy to use getTopics API, iterate thru the response topic array and determine if a topic exist. Just wanted to make sure I dont write something, if it exists already.

Sahas
  • 3,046
  • 6
  • 32
  • 53

3 Answers3

3

Is there a flag that can implicitly create a topic when publishing a message or Is there an API to check if a topic exist already?

I believe the problem you'll run into is that if a message is published to a topic that doesn't exist, it is immediately dropped. So, it won't hang around and wait for a subscription to be created; it'll just disappear.

However, gcloud-node does have methods that will create a topic if necessary:

var topic = pubsub.topic('topic-that-maybe-exists');
topic.get({ autoCreate: true }, function(err, topic) {
  // topic.publish(...
});

In fact, almost all gcloud-node objects have the get method that will work the same way as above, i.e. a Pub/Sub subscription or a Storage bucket or a BigQuery dataset, etc.

Here's a link to the topic.get() method in the docs: https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.37.0/pubsub/topic?method=get

Stephen
  • 5,710
  • 1
  • 24
  • 32
2

Personally use this one

const topic = pubsub.topic('topic-that-maybe-exists');
const [exists] = await topic.exists();
if (!exists) {
   await topic.create();
}
kitta
  • 1,723
  • 3
  • 23
  • 33
1

ran into this recently, and the accepted answer runs you into http 429 errors. topic.get is an administrative function which has a significantly lower rate limit than normal functions. You should only call them when neccessary eg. error code 404 during publish (topic doesn't exist), something like so:

topic.publish(payload, (err) => {
  if(err && err.code === 404){
    topic.get({ autoCreate: true }, (err, topic) => {
      topic.publish(payload)
    });
  }
});
ArcQ
  • 31
  • 3