shellphone.app/app/onboarding/api/queue/set-twilio-webhooks.ts

56 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-08-03 13:03:10 +00:00
import { getConfig } from "blitz";
import { Queue } from "quirrel/blitz";
import twilio from "twilio";
2021-07-31 14:33:18 +00:00
2021-08-01 10:46:10 +00:00
import db from "../../../../db";
2021-07-31 14:33:18 +00:00
type Payload = {
2021-08-05 17:07:15 +00:00
organizationId: string;
phoneNumberId: string;
};
2021-07-31 14:33:18 +00:00
2021-08-03 13:03:10 +00:00
const { serverRuntimeConfig } = getConfig();
2021-08-05 17:07:15 +00:00
const setTwilioWebhooks = Queue<Payload>("api/queue/set-twilio-webhooks", async ({ organizationId, phoneNumberId }) => {
const phoneNumber = await db.phoneNumber.findFirst({
where: { id: phoneNumberId, organizationId },
include: { organization: true },
});
if (!phoneNumber) {
return;
}
2021-08-05 17:07:15 +00:00
const organization = phoneNumber.organization;
if (!organization.twilioAccountSid || !organization.twilioAuthToken) {
return;
}
const twimlApp = organization.twimlAppSid
? await twilio(organization.twilioAccountSid, organization.twilioAuthToken)
.applications.get(organization.twimlAppSid)
.fetch()
: await twilio(organization.twilioAccountSid, organization.twilioAuthToken).applications.create({
2021-08-03 13:03:10 +00:00
friendlyName: "Shellphone",
smsUrl: `https://${serverRuntimeConfig.app.baseUrl}/api/webhook/incoming-message`,
2021-08-01 14:03:49 +00:00
smsMethod: "POST",
2021-08-03 13:03:10 +00:00
voiceUrl: `https://${serverRuntimeConfig.app.baseUrl}/api/webhook/incoming-call`,
2021-08-01 14:03:49 +00:00
voiceMethod: "POST",
});
const twimlAppSid = twimlApp.sid;
2021-07-31 14:33:18 +00:00
2021-08-01 14:03:49 +00:00
await Promise.all([
2021-08-05 17:07:15 +00:00
db.organization.update({
where: { id: organizationId },
2021-08-01 14:03:49 +00:00
data: { twimlAppSid },
}),
2021-08-05 17:07:15 +00:00
twilio(organization.twilioAccountSid, organization.twilioAuthToken)
.incomingPhoneNumbers.get(phoneNumber.id)
.update({
smsApplicationSid: twimlAppSid,
voiceApplicationSid: twimlAppSid,
}),
2021-08-01 14:03:49 +00:00
]);
});
2021-07-31 14:33:18 +00:00
export default setTwilioWebhooks;