shellphone.app/app/settings/mutations/set-phone-number.ts

52 lines
1.5 KiB
TypeScript
Raw Normal View History

import { resolver } from "blitz";
import { z } from "zod";
2021-08-08 04:34:29 +00:00
import twilio from "twilio";
2021-07-31 14:33:18 +00:00
2021-10-15 23:25:13 +00:00
import db from "db";
import getCurrentUser from "app/users/queries/get-current-user";
2021-08-01 10:46:10 +00:00
import setTwilioWebhooks from "../api/queue/set-twilio-webhooks";
2021-07-31 14:33:18 +00:00
const Body = z.object({
phoneNumberSid: z.string(),
});
2021-07-31 14:33:18 +00:00
2021-08-01 14:01:51 +00:00
export default resolver.pipe(resolver.zod(Body), resolver.authorize(), async ({ phoneNumberSid }, context) => {
2021-08-05 17:07:15 +00:00
const user = await getCurrentUser(null, context);
const organization = user?.memberships[0]!.organization;
2021-08-08 04:34:29 +00:00
if (!user || !organization || !organization.twilioAccountSid || !organization.twilioAuthToken) {
return;
}
2021-08-08 04:34:29 +00:00
const phoneNumbers = await twilio(
organization.twilioAccountSid,
organization.twilioAuthToken,
).incomingPhoneNumbers.list();
2021-08-01 14:01:51 +00:00
const phoneNumber = phoneNumbers.find((phoneNumber) => phoneNumber.sid === phoneNumberSid)!;
2021-08-05 17:07:15 +00:00
const organizationId = organization.id;
2021-08-01 14:01:51 +00:00
await db.phoneNumber.create({
data: {
2021-08-05 17:07:15 +00:00
organizationId,
id: phoneNumberSid,
number: phoneNumber.phoneNumber,
2021-08-01 14:01:51 +00:00
},
});
2021-07-31 14:33:18 +00:00
const mainTwilioClient = twilio(organization.twilioAccountSid, organization.twilioAuthToken);
const apiKey = await mainTwilioClient.newKeys.create({ friendlyName: "Shellphone API key" });
await db.organization.update({
where: { id: organizationId },
data: {
twilioApiKey: apiKey.sid,
twilioApiSecret: apiKey.secret,
},
});
2021-08-05 17:07:15 +00:00
const phoneNumberId = phoneNumberSid;
2021-08-01 14:01:51 +00:00
await Promise.all([
2021-08-05 17:07:15 +00:00
setTwilioWebhooks.enqueue(
{ organizationId, phoneNumberId },
{ id: `set-twilio-webhooks-${organizationId}-${phoneNumberId}` },
),
2021-08-01 14:01:51 +00:00
]);
});