diff --git a/src/GoogleCloudPubSub/GoogleCloudPubSub.ts b/src/GoogleCloudPubSub/GoogleCloudPubSub.ts index 8965110..23c4660 100644 --- a/src/GoogleCloudPubSub/GoogleCloudPubSub.ts +++ b/src/GoogleCloudPubSub/GoogleCloudPubSub.ts @@ -238,8 +238,12 @@ export class GoogleCloudPubSub implements GCPubSub { private async getOrCreateSubscription( name: string, topic: Topic, - options?: GCSubscriptionOptions, + subOptions?: GCSubscriptionOptions, ): Promise { + const options = { + ...subOptions, + get: { autoCreate: true, ...subOptions?.get }, + }; const subscriptionName: string = options?.name ?? this.getSubscriptionName(name); const cachedSubscription: Subscription | undefined = this.subscriptions.get(subscriptionName); @@ -259,6 +263,13 @@ export class GoogleCloudPubSub implements GCPubSub { ); } + if (!exists && !(options.get.autoCreate ?? false)) { + /** + * If autoCreate mode is disabled then do not create the subscription + */ + throw new Error(`[@algoan/pubsub] The subscription ${subscriptionName} is not found in topic ${topic.name}`); + } + const [subscription]: GetSubscriptionResponse | CreateSubscriptionResponse = exists ? await sub.get(options?.get) : await sub.create(options?.create); diff --git a/test/GoogleCloudPubSub.test.ts b/test/GoogleCloudPubSub.test.ts index 132c7e5..939e315 100644 --- a/test/GoogleCloudPubSub.test.ts +++ b/test/GoogleCloudPubSub.test.ts @@ -553,3 +553,40 @@ test('GPS012 - should properly listen to the already created subscription', asyn t.true(isTopicExisting); t.true(isSubscriptionExisting); }); + +test('GPS013 - should throw an error because the subscription is not created', async (t: ExecutionContext): Promise => { + const subscriptionName: string = generateRandomTopicName(); + const topicName: string = generateRandomTopicName(); + const pubsub: GCPubSub = PubSubFactory.create({ + transport: Transport.GOOGLE_PUBSUB, + options: { + projectId, + topicsPrefix: 'algoan', + topicsSeparator: '-', + }, + }); + + const [[createdTopic]] = await Promise.all([pubsub.client.createTopic(topicName)]); + try { + await pubsub.listen(subscriptionName, { + options: { + topicName: createdTopic.name, + topicOptions: { + autoCreate: false, + }, + subscriptionOptions: { + get: { + autoCreate: false, + }, + }, + }, + }); + + t.fail('This promise is not supposed to be resolved, since the subscription does not exist!'); + } catch (err) { + t.is( + (err as Error).message, + `[@algoan/pubsub] The subscription ${subscriptionName} is not found in topic projects/${projectId}/topics/${topicName}`, + ); + } +});