2022-05-22 11:04:26 +00:00
|
|
|
import type { LoaderFunction } from "@remix-run/node";
|
|
|
|
import { json } from "superjson-remix";
|
|
|
|
import { parsePhoneNumber } from "awesome-phonenumber";
|
|
|
|
import { type Message, Prisma } from "@prisma/client";
|
|
|
|
|
|
|
|
import db from "~/utils/db.server";
|
|
|
|
import { requireLoggedIn } from "~/utils/auth.server";
|
2022-06-11 00:09:37 +00:00
|
|
|
import { redirect } from "@remix-run/node";
|
2022-05-22 11:04:26 +00:00
|
|
|
|
|
|
|
type ConversationType = {
|
|
|
|
recipient: string;
|
|
|
|
formattedPhoneNumber: string;
|
|
|
|
messages: Message[];
|
|
|
|
};
|
|
|
|
|
|
|
|
export type ConversationLoaderData = {
|
|
|
|
conversation: ConversationType;
|
|
|
|
};
|
|
|
|
|
|
|
|
const loader: LoaderFunction = async ({ request, params }) => {
|
2022-06-11 00:09:37 +00:00
|
|
|
const { twilio } = await requireLoggedIn(request);
|
|
|
|
if (!twilio) {
|
|
|
|
return redirect("/messages");
|
|
|
|
}
|
|
|
|
|
|
|
|
const twilioAccountSid = twilio.accountSid;
|
2022-05-22 11:04:26 +00:00
|
|
|
const recipient = decodeURIComponent(params.recipient ?? "");
|
|
|
|
const conversation = await getConversation(recipient);
|
|
|
|
|
|
|
|
return json<ConversationLoaderData>({ conversation });
|
|
|
|
|
|
|
|
async function getConversation(recipient: string): Promise<ConversationType> {
|
|
|
|
const phoneNumber = await db.phoneNumber.findUnique({
|
2022-06-11 00:09:37 +00:00
|
|
|
where: { twilioAccountSid_isCurrent: { twilioAccountSid, isCurrent: true } },
|
2022-05-22 11:04:26 +00:00
|
|
|
});
|
|
|
|
if (!phoneNumber || phoneNumber.isFetchingMessages) {
|
|
|
|
throw new Error("unreachable");
|
|
|
|
}
|
|
|
|
|
|
|
|
const formattedPhoneNumber = parsePhoneNumber(recipient).getNumber("international");
|
|
|
|
const messages = await db.message.findMany({
|
|
|
|
where: {
|
|
|
|
phoneNumberId: phoneNumber.id,
|
|
|
|
OR: [{ from: recipient }, { to: recipient }],
|
|
|
|
},
|
|
|
|
orderBy: { sentAt: Prisma.SortOrder.asc },
|
|
|
|
});
|
|
|
|
return {
|
|
|
|
recipient,
|
|
|
|
formattedPhoneNumber,
|
|
|
|
messages,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
export default loader;
|