firebase Google云发布/订阅获取或创建订阅

uinbv5nw  于 2022-11-17  发布在  Go
关注(0)|答案(2)|浏览(212)

我有两个工作位的代码如下。
这会取得现有的订阅:

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命令,它将获得订阅并在必要时创建它?
短暂性脑缺血

z9gpfhce

z9gpfhce1#

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

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导入并返回数组中的最后一项

jrcvhitl

jrcvhitl2#

正确的方式

const subscription = this.topic.subscription("name");
const [exists] = await subscription.exists();
if (!exists) {
   await subscription.create();
}

相关问题