shellphone.app/app/messages/api/queue/fetch-messages.ts

45 lines
1.3 KiB
TypeScript
Raw Normal View History

import { Queue } from "quirrel/blitz";
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message";
2021-07-31 14:33:18 +00:00
2021-08-01 10:46:10 +00:00
import db from "../../../../db";
import insertMessagesQueue from "./insert-messages";
import getTwilioClient from "../../../../integrations/twilio";
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 fetchMessagesQueue = Queue<Payload>("api/queue/fetch-messages", async ({ organizationId, phoneNumberId }) => {
const phoneNumber = await db.phoneNumber.findFirst({
where: { id: phoneNumberId, organizationId },
include: { organization: true },
});
if (!phoneNumber) {
return;
}
const organization = phoneNumber.organization;
const twilioClient = getTwilioClient(organization);
2021-08-01 14:01:51 +00:00
const [sent, received] = await Promise.all([
twilioClient.messages.list({ from: phoneNumber.number }),
twilioClient.messages.list({ to: phoneNumber.number }),
]);
2021-08-01 14:01:51 +00:00
const messagesSent = sent.filter((message) => message.direction.startsWith("outbound"));
const messagesReceived = received.filter((message) => message.direction === "inbound");
const messages = [...messagesSent, ...messagesReceived];
2021-07-31 14:33:18 +00:00
await insertMessagesQueue.enqueue(
{
2021-08-05 17:07:15 +00:00
organizationId,
phoneNumberId,
2021-07-31 14:33:18 +00:00
messages,
},
{
2021-08-05 17:07:15 +00:00
id: `insert-messages-${organizationId}-${phoneNumberId}`,
2021-08-01 12:04:04 +00:00
},
);
});
2021-07-31 14:33:18 +00:00
export default fetchMessagesQueue;