Refactors twilio provider (#3604)

Prevents multiple twilio redeclarations

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
pull/3609/head
Omar López 2022-07-30 10:02:34 -06:00 committed by GitHub
parent dba48ab852
commit c9d7412a43
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 25 additions and 15 deletions

View File

@ -1,21 +1,29 @@
import twilio from "twilio";
import TwilioClient 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;
declare global {
// eslint-disable-next-line no-var
var twilio: TwilioClient.Twilio | undefined;
}
client = twilio(TWILIO_SID, TWILIO_TOKEN);
} else {
console.error("Twilio credentials are missing from the .env file");
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" });
};