2021-07-31 15:57:43 +00:00
|
|
|
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-30 12:53:21 +00:00
|
|
|
import db, { Message } from "../../../../db";
|
2021-08-01 10:46:10 +00:00
|
|
|
import { encrypt } from "../../../../db/_encryption";
|
2021-08-30 12:53:21 +00:00
|
|
|
import { translateMessageDirection, translateMessageStatus } 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 15:57:43 +00:00
|
|
|
messages: MessageInstance[];
|
|
|
|
};
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-05 17:07:15 +00:00
|
|
|
const insertMessagesQueue = Queue<Payload>(
|
|
|
|
"api/queue/insert-messages",
|
|
|
|
async ({ messages, organizationId, phoneNumberId }) => {
|
|
|
|
const phoneNumber = await db.phoneNumber.findFirst({
|
|
|
|
where: { id: phoneNumberId, organizationId },
|
|
|
|
include: { organization: true },
|
|
|
|
});
|
|
|
|
if (!phoneNumber) {
|
|
|
|
return;
|
|
|
|
}
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-05 17:07:15 +00:00
|
|
|
const sms = messages
|
2021-08-08 05:34:15 +00:00
|
|
|
.map<Message>((message) => ({
|
|
|
|
id: message.sid,
|
2021-08-05 17:07:15 +00:00
|
|
|
organizationId,
|
|
|
|
phoneNumberId: phoneNumber.id,
|
|
|
|
content: encrypt(message.body, phoneNumber.organization.encryptionKey),
|
|
|
|
from: message.from,
|
|
|
|
to: message.to,
|
2021-08-30 12:53:21 +00:00
|
|
|
status: translateMessageStatus(message.status),
|
|
|
|
direction: translateMessageDirection(message.direction),
|
2021-08-05 17:07:15 +00:00
|
|
|
sentAt: new Date(message.dateCreated),
|
|
|
|
}))
|
|
|
|
.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-13 17:15:35 +00:00
|
|
|
await db.message.createMany({ data: sms, skipDuplicates: true });
|
2021-08-05 17:07:15 +00:00
|
|
|
},
|
|
|
|
);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
export default insertMessagesQueue;
|