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

46 lines
1.0 KiB
TypeScript
Raw Normal View History

import { Queue } from "quirrel/blitz";
import twilio from "twilio";
2021-07-31 14:33:18 +00:00
2021-08-01 10:46:10 +00:00
import db from "../../../../db";
2021-07-31 14:33:18 +00:00
type Payload = {
id: string;
customerId: string;
to: string;
content: string;
};
2021-07-31 14:33:18 +00:00
const sendMessageQueue = Queue<Payload>(
"api/queue/send-message",
async ({ id, customerId, to, content }) => {
const [customer, phoneNumber] = await Promise.all([
db.customer.findFirst({ where: { id: customerId } }),
db.phoneNumber.findFirst({ where: { customerId } }),
]);
if (!customer || !customer.accountSid || !customer.authToken || !phoneNumber) {
return;
}
2021-07-31 14:33:18 +00:00
2021-08-01 07:40:18 +00:00
try {
const message = await twilio(customer.accountSid, customer.authToken).messages.create({
2021-08-01 07:40:18 +00:00
body: content,
to,
from: phoneNumber.phoneNumber,
2021-08-01 07:40:18 +00:00
});
await db.message.update({
where: { id },
data: { twilioSid: message.sid },
});
} catch (error) {
// TODO: handle twilio error
console.log(error.code); // 21211
console.log(error.moreInfo); // https://www.twilio.com/docs/errors/21211
}
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;