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

76 lines
2.0 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";
import { type Message, Prisma, Direction } from "@prisma/client";
2022-05-14 10:22:06 +00:00
import db from "~/utils/db.server";
import { requireLoggedIn, type SessionData } from "~/utils/auth.server";
2022-05-14 10:22:06 +00:00
export type MessagesLoaderData = {
2022-05-19 23:16:38 +00:00
user: { hasPhoneNumber: boolean };
2022-05-14 10:22:06 +00:00
conversations: Record<string, Conversation> | undefined;
};
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 sessionData = await requireLoggedIn(request);
return json<MessagesLoaderData>({
user: { hasPhoneNumber: Boolean(sessionData.phoneNumber) },
conversations: await getConversations(sessionData.phoneNumber),
2022-05-14 10:22:06 +00:00
});
};
export default loader;
async function getConversations(sessionPhoneNumber: SessionData["phoneNumber"]) {
if (!sessionPhoneNumber) {
return;
}
2022-05-19 23:16:38 +00:00
const phoneNumber = await db.phoneNumber.findUnique({
where: { id: sessionPhoneNumber.id },
2022-05-19 23:16:38 +00:00
});
if (!phoneNumber || phoneNumber.isFetchingMessages) {
return;
}
2022-05-19 23:16:38 +00:00
const messages = await db.message.findMany({
where: { phoneNumberId: phoneNumber.id },
orderBy: { sentAt: Prisma.SortOrder.desc },
2022-05-19 23:16:38 +00:00
});
let conversations: Record<string, Conversation> = {};
for (const message of messages) {
let recipient: string;
if (message.direction === Direction.Outbound) {
recipient = message.to;
} else {
recipient = message.from;
2022-05-19 23:16:38 +00:00
}
const formattedPhoneNumber = parsePhoneNumber(recipient).getNumber("international");
2022-05-19 23:16:38 +00:00
if (!conversations[recipient]) {
conversations[recipient] = {
recipient,
formattedPhoneNumber,
lastMessage: message,
};
2022-05-19 23:16:38 +00:00
}
if (message.sentAt > conversations[recipient].lastMessage.sentAt) {
conversations[recipient].lastMessage = message;
}
/*conversations[recipient]!.messages.push({
...message,
content: decrypt(message.content, organization.encryptionKey),
});*/
2022-05-19 23:16:38 +00:00
}
2022-05-14 10:22:06 +00:00
return conversations;
}