shellphone.app/app/messages/api/queue/send-message.ts

53 lines
1.4 KiB
TypeScript
Raw Normal View History

import { Queue } from "quirrel/blitz";
2021-07-31 14:33:18 +00:00
2021-08-05 17:07:15 +00:00
import db, { MessageStatus } from "../../../../db";
import getTwilioClient from "../../../../integrations/twilio";
2021-07-31 14:33:18 +00:00
type Payload = {
id: string;
2021-08-05 17:07:15 +00:00
organizationId: string;
phoneNumberId: string;
to: string;
content: string;
};
2021-07-31 14:33:18 +00:00
const sendMessageQueue = Queue<Payload>(
"api/queue/send-message",
2021-08-05 17:07:15 +00:00
async ({ id, organizationId, phoneNumberId, to, content }) => {
const organization = await db.organization.findFirst({
where: { id: organizationId },
include: { phoneNumbers: true },
});
const phoneNumber = organization?.phoneNumbers.find((phoneNumber) => phoneNumber.id === phoneNumberId);
if (!organization || !phoneNumber) {
return;
}
2021-07-31 14:33:18 +00:00
const twilioClient = getTwilioClient(organization);
2021-08-01 07:40:18 +00:00
try {
const message = await twilioClient.messages.create({
2021-08-01 07:40:18 +00:00
body: content,
to,
2021-08-05 17:07:15 +00:00
from: phoneNumber.number,
2021-08-01 07:40:18 +00:00
});
await db.message.update({
2021-08-05 17:07:15 +00:00
where: { organizationId_phoneNumberId_id: { id, organizationId, phoneNumberId } },
data: { id: message.sid },
2021-08-01 07:40:18 +00:00
});
} catch (error) {
// TODO: handle twilio error
console.log(error.code); // 21211
console.log(error.moreInfo); // https://www.twilio.com/docs/errors/21211
2021-08-05 17:07:15 +00:00
await db.message.update({
where: { id },
data: { status: MessageStatus.Error /*errorMessage: "Reason: failed because of"*/ },
});
2021-08-01 07:40:18 +00:00
}
2021-07-31 14:33:18 +00:00
},
{
retry: ["1min"],
2021-08-01 12:04:04 +00:00
},
);
2021-07-31 14:33:18 +00:00
export default sendMessageQueue;