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

39 lines
994 B
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 = {
customerId: string;
};
2021-07-31 14:33:18 +00:00
const fetchCallsQueue = Queue<Payload>("api/queue/fetch-calls", async ({ customerId }) => {
const customer = await db.customer.findFirst({ where: { id: customerId } });
const phoneNumber = await db.phoneNumber.findFirst({ where: { customerId } });
2021-07-31 14:33:18 +00:00
const [callsSent, callsReceived] = await Promise.all([
twilio(customer!.accountSid!, customer!.authToken!).calls.list({
from: phoneNumber!.phoneNumber,
}),
twilio(customer!.accountSid!, customer!.authToken!).calls.list({
to: phoneNumber!.phoneNumber,
}),
]);
2021-07-31 14:33:18 +00:00
const calls = [...callsSent, ...callsReceived].sort(
2021-08-01 12:04:04 +00:00
(a, b) => a.dateCreated.getTime() - b.dateCreated.getTime(),
);
2021-07-31 14:33:18 +00:00
await insertCallsQueue.enqueue(
{
customerId,
calls,
},
{
id: `insert-calls-${customerId}`,
2021-08-01 12:04:04 +00:00
},
);
});
2021-07-31 14:33:18 +00:00
export default fetchCallsQueue;