shellphone.app/app/phone-calls/api/queue/fetch-calls.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

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";
import insertCallsQueue from "./insert-calls";
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-05 17:07:15 +00:00
const fetchCallsQueue = Queue<Payload>("api/queue/fetch-calls", async ({ organizationId, phoneNumberId }) => {
const phoneNumber = await db.phoneNumber.findFirst({
where: { id: phoneNumberId, organizationId },
include: { organization: true },
});
if (!phoneNumber) {
return;
}
const organization = phoneNumber.organization;
if (!organization.twilioAccountSid || !organization.twilioAuthToken) {
return;
}
2021-07-31 14:33:18 +00:00
const [callsSent, callsReceived] = await Promise.all([
2021-08-05 17:07:15 +00:00
twilio(organization.twilioAccountSid, organization.twilioAuthToken).calls.list({
from: phoneNumber.number,
2021-07-31 14:33:18 +00:00
}),
2021-08-05 17:07:15 +00:00
twilio(organization.twilioAccountSid, organization.twilioAuthToken).calls.list({
to: phoneNumber.number,
2021-07-31 14:33:18 +00:00
}),
]);
2021-08-01 14:03:49 +00:00
const calls = [...callsSent, ...callsReceived].sort((a, b) => a.dateCreated.getTime() - b.dateCreated.getTime());
2021-07-31 14:33:18 +00:00
await insertCallsQueue.enqueue(
{
2021-08-05 17:07:15 +00:00
organizationId,
phoneNumberId,
2021-07-31 14:33:18 +00:00
calls,
},
{
2021-08-05 17:07:15 +00:00
id: `insert-calls-${organizationId}-${phoneNumberId}`,
2021-08-01 12:04:04 +00:00
},
);
});
2021-07-31 14:33:18 +00:00
export default fetchCallsQueue;