set api key when setting the phone number to avoid race conditions later when fetching calls and messages

This commit is contained in:
m5r 2021-08-08 13:34:15 +08:00
parent 6ad516a99e
commit 0b34e861e0
3 changed files with 18 additions and 18 deletions

View File

@ -22,15 +22,15 @@ const insertMessagesQueue = Queue<Payload>(
}
const sms = messages
.map<Omit<Message, "id">>((message) => ({
.map<Message>((message) => ({
organizationId,
id: message.sid,
phoneNumberId: phoneNumber.id,
content: encrypt(message.body, phoneNumber.organization.encryptionKey),
from: message.from,
to: message.to,
status: translateStatus(message.status),
direction: translateDirection(message.direction),
twilioSid: message.sid,
sentAt: new Date(message.dateCreated),
}))
.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());

View File

@ -1,9 +1,10 @@
import { getConfig } from "blitz";
import { Queue } from "quirrel/blitz";
import twilio from "twilio";
import type twilio from "twilio";
import type { ApplicationInstance } from "twilio/lib/rest/api/v2010/account/application";
import db from "../../../../db";
import getTwilioClient from "../../../../integrations/twilio";
type Payload = {
organizationId: string;
@ -22,27 +23,16 @@ const setTwilioWebhooks = Queue<Payload>("api/queue/set-twilio-webhooks", async
}
const organization = phoneNumber.organization;
if (!organization.twilioAccountSid || !organization.twilioAuthToken) {
return;
}
const mainTwilioClient = twilio(organization.twilioAccountSid, organization.twilioAuthToken);
const [twimlApp, apiKey] = await Promise.all([
getTwimlApplication(mainTwilioClient, organization.twimlAppSid),
mainTwilioClient.newKeys.create({ friendlyName: "Shellphone API key" }),
]);
const twilioClient = getTwilioClient(organization);
const twimlApp = await getTwimlApplication(twilioClient, organization.twimlAppSid);
const twimlAppSid = twimlApp.sid;
await Promise.all([
db.organization.update({
where: { id: organizationId },
data: {
twimlAppSid,
twilioApiKey: apiKey.sid,
twilioApiSecret: apiKey.secret,
},
data: { twimlAppSid },
}),
mainTwilioClient.incomingPhoneNumbers.get(phoneNumber.id).update({
twilioClient.incomingPhoneNumbers.get(phoneNumber.id).update({
smsApplicationSid: twimlAppSid,
voiceApplicationSid: twimlAppSid,
}),

View File

@ -34,6 +34,16 @@ export default resolver.pipe(resolver.zod(Body), resolver.authorize(), async ({
});
context.session.$setPrivateData({ hasCompletedOnboarding: true });
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,
},
});
const phoneNumberId = phoneNumberSid;
await Promise.all([
fetchMessagesQueue.enqueue(