Skip to content

Commit 90da8c7

Browse files
committed
♻️ pubsub timeout
1 parent eb646fd commit 90da8c7

File tree

2 files changed

+12
-16
lines changed

2 files changed

+12
-16
lines changed

src/models/pubsub-client.model.ts

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { PubSub } from "@google-cloud/pubsub";
2+
import { timeout } from "../util/timeout";
23
import { PubSubContactsMessage } from "./pubsub-contacts-message.model";
3-
import { ServerError } from "./server-error.model";
44

55
const PUBLISH_TIMEOUT = 10_000;
6+
67
export class PubSubClient {
78
private client: PubSub;
89
private topicName: string;
@@ -17,27 +18,16 @@ export class PubSubClient {
1718
throw new Error("No pubsub topic name provided.");
1819
}
1920

20-
const timeout = (ms: number) =>
21-
new Promise((_, reject) =>
22-
setTimeout(
23-
() =>
24-
reject(
25-
new ServerError(
26-
500,
27-
"Could not publish message in time, did you forget to run gcloud auth application-default login?"
28-
)
29-
),
30-
ms
31-
)
32-
);
33-
3421
const json = JSON.stringify(message);
3522
const dataBuffer = Buffer.from(json);
3623
const topic = this.client.topic(this.topicName);
3724

3825
await Promise.race([
3926
topic.publishMessage({ data: dataBuffer }),
40-
timeout(PUBLISH_TIMEOUT),
27+
timeout(
28+
PUBLISH_TIMEOUT,
29+
"Could not publish message in time. Did you forget to authenticate with GCP? (gcloud auth application-default login)"
30+
),
4131
]);
4232
}
4333
}

src/util/timeout.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { ServerError } from "../models";
2+
3+
export const timeout = (timeMs: number, errorMessage: string) =>
4+
new Promise((_, reject) =>
5+
setTimeout(() => reject(new ServerError(500, errorMessage)), timeMs)
6+
);

0 commit comments

Comments
 (0)