Skip to content

Scheduling infrastructure for absolutely everyone.

Refactors twilio provider (#3604)

Omar Lópezc9d7412a4342
diff --git a/packages/features/ee/workflows/lib/reminders/smsProviders/twilioProvider.ts b/packages/features/ee/workflows/lib/reminders/smsProviders/twilioProvider.ts
index 5f9ae2bfff0..4eab4cde6e3 100644
--- a/packages/features/ee/workflows/lib/reminders/smsProviders/twilioProvider.ts
+++ b/packages/features/ee/workflows/lib/reminders/smsProviders/twilioProvider.ts
@@ -1,21 +1,29 @@
-import twilio from "twilio";
-
-let TWILIO_SID, TWILIO_TOKEN, TWILIO_MESSAGING_SID: string, client: twilio.Twilio;
-// Only assign the API keys if they exist in .env
-if (process.env.TWILIO_SID && process.env.TWILIO_TOKEN && process.env.TWILIO_MESSAGING_SID) {
- TWILIO_SID = process.env.TWILIO_SID;
- TWILIO_TOKEN = process.env.TWILIO_TOKEN;
- TWILIO_MESSAGING_SID = process.env.TWILIO_MESSAGING_SID;
-
- client = twilio(TWILIO_SID, TWILIO_TOKEN);
-} else {
- console.error("Twilio credentials are missing from the .env file");
+import TwilioClient from "twilio";
+
+declare global {
+ // eslint-disable-next-line no-var
+ var twilio: TwilioClient.Twilio | undefined;
+}
+
+export const twilio =
+ globalThis.twilio ||
+ (process.env.TWILIO_SID && process.env.TWILIO_TOKEN && process.env.TWILIO_MESSAGING_SID)
+ ? TwilioClient(process.env.TWILIO_SID, process.env.TWILIO_TOKEN)
+ : undefined;
+
+if (process.env.NODE_ENV !== "production") {
+ globalThis.twilio = twilio;
+}
+
+function assertTwilio(twilio: TwilioClient.Twilio | undefined): asserts twilio is TwilioClient.Twilio {
+ if (!twilio) throw new Error("Twilio credentials are missing from the .env file");
}
export const sendSMS = async (phoneNumber: string, body: string) => {
- const response = await client.messages.create({
+ assertTwilio(twilio);
+ const response = await twilio.messages.create({
body: body,
- messagingServiceSid: TWILIO_MESSAGING_SID,
+ messagingServiceSid: process.env.TWILIO_MESSAGING_SID,
to: phoneNumber,
});
@@ -23,9 +31,10 @@ export const sendSMS = async (phoneNumber: string, body: string) => {
};
export const scheduleSMS = async (phoneNumber: string, body: string, scheduledDate: Date) => {
- const response = await client.messages.create({
+ assertTwilio(twilio);
+ const response = await twilio.messages.create({
body: body,
- messagingServiceSid: TWILIO_MESSAGING_SID,
+ messagingServiceSid: process.env.TWILIO_MESSAGING_SID,
to: phoneNumber,
scheduleType: "fixed",
sendAt: scheduledDate,
@@ -35,5 +44,6 @@ export const scheduleSMS = async (phoneNumber: string, body: string, scheduledDa
};
export const cancelSMS = async (referenceId: string) => {
- await client.messages(referenceId).update({ status: "canceled" });
+ assertTwilio(twilio);
+ await twilio.messages(referenceId).update({ status: "canceled" });
};