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

41 lines
1.3 KiB
TypeScript
Raw Normal View History

import { resolver } from "blitz";
import { z } from "zod";
import twilio from "twilio";
2021-07-31 14:33:18 +00:00
import db from "../../../db";
import getCurrentCustomer from "../../customers/queries/get-current-customer";
import fetchMessagesQueue from "../../api/queue/fetch-messages";
import fetchCallsQueue from "../../api/queue/fetch-calls";
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
export default resolver.pipe(
resolver.zod(Body),
resolver.authorize(),
async ({ phoneNumberSid }, context) => {
const customer = await getCurrentCustomer(null, context);
const customerId = customer!.id;
2021-07-31 14:33:18 +00:00
const phoneNumbers = await twilio(
customer!.accountSid!,
customer!.authToken!
).incomingPhoneNumbers.list();
const phoneNumber = phoneNumbers.find((phoneNumber) => phoneNumber.sid === phoneNumberSid)!;
2021-07-31 14:33:18 +00:00
await db.phoneNumber.create({
data: {
customerId,
phoneNumberSid,
phoneNumber: phoneNumber.phoneNumber,
},
});
2021-07-31 14:33:18 +00:00
await Promise.all([
fetchMessagesQueue.enqueue({ customerId }, { id: `fetch-messages-${customerId}` }),
fetchCallsQueue.enqueue({ customerId }, { id: `fetch-messages-${customerId}` }),
setTwilioWebhooks.enqueue({ customerId }, { id: `set-twilio-webhooks-${customerId}` }),
]);
2021-07-31 14:33:18 +00:00
}
);