multi tenancy stuff

This commit is contained in:
m5r
2021-08-06 01:07:15 +08:00
parent b54f9ef43c
commit d20eeb0617
51 changed files with 907 additions and 2542 deletions

View File

@ -1,40 +1,46 @@
import { Queue } from "quirrel/blitz";
import twilio from "twilio";
import db from "../../../../db";
import db, { MessageStatus } from "../../../../db";
type Payload = {
id: string;
customerId: string;
organizationId: string;
phoneNumberId: string;
to: string;
content: string;
};
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) {
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) {
return;
}
try {
const message = await twilio(customer.accountSid, customer.authToken).messages.create({
const message = await twilio(organization.twilioAccountSid, organization.twilioAuthToken).messages.create({
body: content,
to,
from: phoneNumber.phoneNumber,
from: phoneNumber.number,
});
await db.message.update({
where: { id },
data: { twilioSid: message.sid },
where: { organizationId_phoneNumberId_id: { id, organizationId, phoneNumberId } },
data: { id: message.sid },
});
} catch (error) {
// TODO: handle twilio error
console.log(error.code); // 21211
console.log(error.moreInfo); // https://www.twilio.com/docs/errors/21211
await db.message.update({
where: { id },
data: { status: MessageStatus.Error /*errorMessage: "Reason: failed because of"*/ },
});
}
},
{