shellphone.app/app/messages/api/queue/insert-incoming-message.ts

53 lines
1.5 KiB
TypeScript
Raw Normal View History

import { Queue } from "quirrel/blitz";
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message";
import db from "../../../../db";
import { encrypt } from "../../../../db/_encryption";
2021-08-05 17:07:15 +00:00
import notifyIncomingMessageQueue from "./notify-incoming-message";
import getTwilioClient, { translateMessageDirection, translateMessageStatus } from "../../../../integrations/twilio";
type Payload = {
2021-08-05 17:07:15 +00:00
organizationId: string;
phoneNumberId: string;
messageSid: MessageInstance["sid"];
};
const insertIncomingMessageQueue = Queue<Payload>(
"api/queue/insert-incoming-message",
2021-08-05 17:07:15 +00:00
async ({ messageSid, organizationId, phoneNumberId }) => {
const organization = await db.organization.findFirst({
where: { id: organizationId },
});
if (!organization) {
return;
}
const twilioClient = getTwilioClient(organization);
const message = await twilioClient.messages.get(messageSid).fetch();
await db.message.create({
data: {
2021-08-05 17:07:15 +00:00
organizationId,
phoneNumberId,
id: messageSid,
to: message.to,
from: message.from,
status: translateMessageStatus(message.status),
direction: translateMessageDirection(message.direction),
sentAt: new Date(message.dateCreated),
2021-08-05 17:07:15 +00:00
content: encrypt(message.body, organization.encryptionKey),
},
});
2021-08-05 17:07:15 +00:00
await notifyIncomingMessageQueue.enqueue(
{
messageSid,
organizationId,
phoneNumberId,
},
2021-08-05 17:07:15 +00:00
{ id: `notify-${messageSid}-${organizationId}-${phoneNumberId}` },
);
2021-08-01 12:04:04 +00:00
},
);
export default insertIncomingMessageQueue;