Skip to content

Commit c3f1ed2

Browse files
committed
🧑‍💻 add race condition to catch missing application-default reauth
1 parent 414bd1a commit c3f1ed2

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/models/pubsub-client.model.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { PubSub } from "@google-cloud/pubsub";
22
import { PubSubContactsMessage } from "./pubsub-contacts-message.model";
3+
import { ServerError } from "./server-error.model";
34

5+
const PUBLISH_TIMEOUT = 10_000;
46
export class PubSubClient {
57
private client: PubSub;
68
private topicName: string;
@@ -15,9 +17,27 @@ export class PubSubClient {
1517
throw new Error("No pubsub topic name provided.");
1618
}
1719

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+
1834
const json = JSON.stringify(message);
1935
const dataBuffer = Buffer.from(json);
2036
const topic = this.client.topic(this.topicName);
21-
await topic.publishMessage({ data: dataBuffer });
37+
38+
await Promise.race([
39+
topic.publishMessage({ data: dataBuffer }),
40+
timeout(PUBLISH_TIMEOUT),
41+
]);
2242
}
2343
}

0 commit comments

Comments
 (0)