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

66 lines
1.8 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 }) => {
2022-05-21 23:45:13 +00:00
const sessionData = await requireLoggedIn(request);
const phoneNumber =
sessionData.phoneNumber &&
(await db.phoneNumber.findUnique({
where: { id: sessionData.phoneNumber.id },
}));
return json<MessagesLoaderData>({
2022-05-21 23:45:13 +00:00
hasPhoneNumber: Boolean(phoneNumber),
isFetchingMessages: phoneNumber?.isFetchingMessages ?? null,
conversations: await getConversations(phoneNumber),
2022-05-14 10:22:06 +00:00
});
};
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;
}, {});
}