Search code examples
firebasepublish-subscribegoogle-cloud-pubsub

Google Cloud Pub/Sub get or create subscription


I've got two working bits of code as follows.

This gets an existing subscription:

this.pubSubClient = new PubSub()
sub = this.pubSubClient.subscription(appConfig.pubSub.subscription)

The creates and gets a non-existing subscription:

this.pubSubClient = new PubSub()
this.topic = this.pubSubClient.topic(appConfig.pubSub.topic)
[sub] = await this.topic.createSubscription(appConfig.pubSub.subscription)

This all works great. However, the first bit of code causes problems if the subscription does NOT exist (on one environment) and the second bit of code causes problems if the subscription does exist (on another environment).

So I've tried to do this:

let sub

try {
  sub = this.pubSubClient.subscription(appConfig.pubSub.subscription)
  console.log('using existing subscription')
} catch (err) {
  [sub] = await this.topic.createSubscription(appConfig.pubSub.subscription)
  console.log('using created subscription')
}

But the above does not work because the first line of code never triggers an error. It merely fails to ever receive any messages. Is there a command to getOrCreateSubscription that I can use which will get the subscription and create it if necessary?


Solution

  • Best way seems to be to get subscriptions on the topic of interest and if its not listed then it does not exist so create it else just get it

    const [subscriptions] = await this.topic.getSubscriptions()
    const subs = subscriptions.map(subscription => last(subscription.name.split('/')))
    const subExists = subs.includes(appConfig.pubSub.subscription)
    
    let sub
    
    if (subExists) {
      sub = this.pubSubClient.subscription(appConfig.pubSub.subscription)
      console.log('using existing subscription')
    } else {
      [sub] = await this.topic.createSubscription(appConfig.pubSub.subscription)
      console.log('using created subscription')
    }
    

    FYI last is imported from lodash and returns the last item in an array