shellphone.app/app/messages/mutations/send-message.ts

67 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-08-05 17:07:15 +00:00
import { NotFoundError, resolver } from "blitz";
import { z } from "zod";
2021-07-31 14:33:18 +00:00
import db, { Direction, MessageStatus } from "../../../db";
import { encrypt } from "../../../db/_encryption";
2021-08-01 10:46:10 +00:00
import sendMessageQueue from "../../messages/api/queue/send-message";
2021-08-01 07:40:18 +00:00
import appLogger from "../../../integrations/logger";
import getTwilioClient from "../../../integrations/twilio";
2021-08-01 07:40:18 +00:00
const logger = appLogger.child({ mutation: "send-message" });
2021-07-31 14:33:18 +00:00
const Body = z.object({
content: z.string(),
to: z.string(),
});
2021-07-31 14:33:18 +00:00
2021-08-01 14:03:49 +00:00
export default resolver.pipe(resolver.zod(Body), resolver.authorize(), async ({ content, to }, context) => {
2021-08-05 17:07:15 +00:00
const organizationId = context.session.orgId;
const organization = await db.organization.findFirst({
where: { id: organizationId },
include: { phoneNumbers: true },
});
if (!organization) {
throw new NotFoundError();
}
const twilioClient = getTwilioClient(organization);
2021-08-01 14:03:49 +00:00
try {
await twilioClient.lookups.v1.phoneNumbers(to).fetch();
2021-08-01 14:03:49 +00:00
} catch (error) {
logger.error(error);
return;
}
2021-08-01 07:40:18 +00:00
2021-08-05 17:07:15 +00:00
const phoneNumber = organization.phoneNumbers[0];
if (!phoneNumber) {
return;
}
2021-07-31 14:33:18 +00:00
2021-08-05 17:07:15 +00:00
const phoneNumberId = phoneNumber.id;
2021-08-01 14:03:49 +00:00
const message = await db.message.create({
data: {
2021-08-05 17:07:15 +00:00
organizationId,
phoneNumberId,
2021-08-01 14:03:49 +00:00
to,
2021-08-05 17:07:15 +00:00
from: phoneNumber.number,
2021-08-01 14:03:49 +00:00
direction: Direction.Outbound,
status: MessageStatus.Queued,
2021-08-05 17:07:15 +00:00
content: encrypt(content, organization.encryptionKey),
2021-08-01 14:03:49 +00:00
sentAt: new Date(),
},
});
2021-07-31 14:33:18 +00:00
2021-08-01 14:03:49 +00:00
await sendMessageQueue.enqueue(
{
id: message.id,
2021-08-05 17:07:15 +00:00
organizationId,
phoneNumberId,
2021-08-01 14:03:49 +00:00
to,
content,
},
{
2021-08-05 17:07:15 +00:00
id: `insert-${message.id}-${organizationId}-${phoneNumberId}`,
2021-08-01 14:03:49 +00:00
},
);
});