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

62 lines
1.6 KiB
TypeScript
Raw Normal View History

import { resolver } from "blitz";
import { z } from "zod";
2021-08-01 07:40:18 +00:00
import twilio from "twilio";
2021-07-31 14:33:18 +00:00
import db, { Direction, MessageStatus } from "../../../db";
import getCurrentCustomer from "../../customers/queries/get-current-customer";
import getCustomerPhoneNumber from "../../phone-numbers/queries/get-customer-phone-number";
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";
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) => {
const customer = await getCurrentCustomer(null, context);
if (!customer || !customer.accountSid || !customer.authToken) {
return;
}
2021-08-01 14:03:49 +00:00
try {
await twilio(customer.accountSid, customer.authToken).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
const customerId = customer.id;
2021-08-01 14:03:49 +00:00
const customerPhoneNumber = await getCustomerPhoneNumber({ customerId }, context);
if (!customerPhoneNumber) {
return;
}
2021-07-31 14:33:18 +00:00
2021-08-01 14:03:49 +00:00
const message = await db.message.create({
data: {
customerId,
to,
from: customerPhoneNumber.phoneNumber,
2021-08-01 14:03:49 +00:00
direction: Direction.Outbound,
status: MessageStatus.Queued,
content: encrypt(content, customer.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,
customerId,
to,
content,
},
{
2021-08-01 16:28:47 +00:00
id: `insert-${message.id}`,
2021-08-01 14:03:49 +00:00
},
);
});