Skip to content

Commit

Permalink
fix: do not create the subscription if subscription is not present
Browse files Browse the repository at this point in the history
  • Loading branch information
gitSambhal authored Jan 2, 2024
1 parent 542a9c9 commit 22ccc05
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/GoogleCloudPubSub/GoogleCloudPubSub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,12 @@ export class GoogleCloudPubSub implements GCPubSub {
private async getOrCreateSubscription(
name: string,
topic: Topic,
options?: GCSubscriptionOptions,
subOptions?: GCSubscriptionOptions,
): Promise<Subscription> {
const options = {
...subOptions,
get: { autoCreate: true, ...subOptions?.get },
};
const subscriptionName: string = options?.name ?? this.getSubscriptionName(name);
const cachedSubscription: Subscription | undefined = this.subscriptions.get(subscriptionName);

Expand All @@ -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);
Expand Down
37 changes: 37 additions & 0 deletions test/GoogleCloudPubSub.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> => {
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}`,
);
}
});

0 comments on commit 22ccc05

Please sign in to comment.