gcloud check if a topic exist and ability to reuse the topic
Asked Answered
C

3

7

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.

Crocodile answered 10/8, 2016 at 4:7 Comment(0)
E
4

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

Excoriate answered 10/8, 2016 at 16:0 Comment(1)
Is it possible to do the autoCreate:true equivalent in Java?Sension
P
4

Personally use this one

const topic = pubsub.topic('topic-that-maybe-exists');
const [exists] = await topic.exists();
if (!exists) {
   await topic.create();
}
Pentobarbital answered 10/11, 2022 at 2:54 Comment(0)
M
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)
    });
  }
});
Mozzarella answered 22/6, 2017 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.