Google Cloud Pub/Sub 获取或创建订阅

Google Cloud Pub/Sub get or create subscription

我有 2 个工作代码如下。

这获取现有订阅:

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

创建并获取一个不存在的订阅:

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

这一切都很好。但是,如果订阅不存在(在一个环境中),则第一位代码会导致问题,如果订阅存在(在另一个环境中),则第二位代码会导致问题。

所以我尝试这样做:

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')
}

但是上面的代码不起作用,因为第一行代码永远不会触发错误。它只是没有收到任何消息。是否有我可以使用的 getOrCreateSubscription 命令,它将获得订阅并在必要时创建它?

TIA

最好的方法似乎是订阅感兴趣的主题,如果它没有列出,那么它不存在,所以创建它,否则就得到它

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 是从 lodash 导入的,returns 数组中的最后一项