2021-07-31 15:57:43 +00:00
|
|
|
import { Queue } from "quirrel/blitz";
|
|
|
|
import twilio from "twilio";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-05 17:07:15 +00:00
|
|
|
import db, { MessageStatus } from "../../../../db";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
type Payload = {
|
2021-07-31 15:57:43 +00:00
|
|
|
id: string;
|
2021-08-05 17:07:15 +00:00
|
|
|
organizationId: string;
|
|
|
|
phoneNumberId: string;
|
2021-07-31 15:57:43 +00:00
|
|
|
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 || !organization.twilioAccountSid || !organization.twilioAuthToken || !phoneNumber) {
|
2021-08-02 10:02:49 +00:00
|
|
|
return;
|
|
|
|
}
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-08-01 07:40:18 +00:00
|
|
|
try {
|
2021-08-05 17:07:15 +00:00
|
|
|
const message = await twilio(organization.twilioAccountSid, organization.twilioAuthToken).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 15:57:43 +00:00
|
|
|
);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
export default sendMessageQueue;
|