shellphone.app/app/features/messages/loaders/messages.ts

69 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-05-14 10:22:06 +00:00
import type { LoaderFunction } from "@remix-run/node";
2022-05-19 23:16:38 +00:00
import { json } from "superjson-remix";
import { parsePhoneNumber } from "awesome-phonenumber";
2022-05-21 23:45:13 +00:00
import { type Message, type PhoneNumber, Prisma } from "@prisma/client";
2022-05-14 10:22:06 +00:00
import db from "~/utils/db.server";
2022-05-21 23:45:13 +00:00
import { requireLoggedIn } from "~/utils/auth.server";
2022-05-14 10:22:06 +00:00
export type MessagesLoaderData = {
2022-05-21 23:45:13 +00:00
hasPhoneNumber: boolean;
isFetchingMessages: boolean | null;
conversations: Conversations | undefined;
2022-05-14 10:22:06 +00:00
};
type Conversation = {
recipient: string;
formattedPhoneNumber: string;
2022-05-19 23:16:38 +00:00
lastMessage: Message;
2022-05-14 10:22:06 +00:00
};
const loader: LoaderFunction = async ({ request }) => {
const { twilio } = await requireLoggedIn(request);
const phoneNumber = await db.phoneNumber.findUnique({
where: { twilioAccountSid_isCurrent: { twilioAccountSid: twilio?.accountSid ?? "", isCurrent: true } },
});
return json<MessagesLoaderData>(
{
hasPhoneNumber: Boolean(phoneNumber),
isFetchingMessages: phoneNumber?.isFetchingMessages ?? null,
conversations: await getConversations(phoneNumber),
},
{
headers: { Vary: "Cookie" },
},
);
};
export default loader;
type Conversations = Record<string, Conversation>;
2022-05-21 23:45:13 +00:00
async function getConversations(phoneNumber: PhoneNumber | null) {
if (!phoneNumber) {
return;
}
2022-05-19 23:16:38 +00:00
const messages = await db.message.findMany({
where: { phoneNumberId: phoneNumber.id },
orderBy: { sentAt: Prisma.SortOrder.desc },
distinct: "recipient",
2022-05-19 23:16:38 +00:00
});
return messages.reduce<Conversations>((conversations, message) => {
const recipient = message.recipient;
const formattedPhoneNumber = parsePhoneNumber(recipient).getNumber("international");
2022-05-19 23:16:38 +00:00
conversations[recipient] = {
recipient,
formattedPhoneNumber,
lastMessage: message,
};
/*conversations[recipient]!.messages.push({
...message,
content: decrypt(message.content, organization.encryptionKey),
});*/
return conversations;
}, {});
}