46 lines
1.2 KiB
TypeScript
Raw Normal View History

import { Queue } from "quirrel/blitz";
2021-07-31 22:33:18 +08:00
2021-08-01 18:46:10 +08:00
import db from "../../../../db";
import insertCallsQueue from "./insert-calls";
import getTwilioClient from "../../../../integrations/twilio";
2021-08-31 04:13:40 +08:00
import appLogger from "../../../../integrations/logger";
const logger = appLogger.child({ queue: "fetch-calls" });
2021-07-31 22:33:18 +08:00
type Payload = {
2021-08-06 01:07:15 +08:00
organizationId: string;
phoneNumberId: string;
};
2021-07-31 22:33:18 +08:00
2021-08-06 01:07:15 +08: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) {
2021-08-31 04:13:40 +08:00
logger.warn(`No phone number found with id=${phoneNumberId}, organizationId=${organizationId}`);
2021-08-06 01:07:15 +08:00
return;
}
const organization = phoneNumber.organization;
const twilioClient = getTwilioClient(organization);
2021-07-31 22:33:18 +08:00
const [callsSent, callsReceived] = await Promise.all([
twilioClient.calls.list({ from: phoneNumber.number }),
twilioClient.calls.list({ to: phoneNumber.number }),
]);
const calls = [...callsSent, ...callsReceived];
2021-07-31 22:33:18 +08:00
await insertCallsQueue.enqueue(
{
2021-08-06 01:07:15 +08:00
organizationId,
phoneNumberId,
2021-07-31 22:33:18 +08:00
calls,
},
{
2021-08-06 01:07:15 +08:00
id: `insert-calls-${organizationId}-${phoneNumberId}`,
2021-08-01 20:04:04 +08:00
},
);
});
2021-07-31 22:33:18 +08:00
export default fetchCallsQueue;