google-cloud-pubsubgcloud-node

gcloud check if a topic exist and ability to reuse the topic


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.


Solution

  • 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