shellphone.app/app/messages/queries/get-conversations.ts

46 lines
1.3 KiB
TypeScript
Raw Normal View History

import { resolver, NotFoundError } from "blitz";
2021-07-31 14:33:18 +00:00
import db, { Direction, Message, Prisma } from "../../../db";
import getCurrentCustomer from "../../customers/queries/get-current-customer";
import { decrypt } from "../../../db/_encryption";
2021-07-31 14:33:18 +00:00
export default resolver.pipe(resolver.authorize(), async (_ = null, context) => {
const customer = await getCurrentCustomer(null, context);
if (!customer) {
throw new NotFoundError();
}
2021-07-31 14:33:18 +00:00
const messages = await db.message.findMany({
where: { customerId: customer.id },
2021-07-31 14:33:18 +00:00
orderBy: { sentAt: Prisma.SortOrder.asc },
});
2021-07-31 14:33:18 +00:00
let conversations: Record<string, Message[]> = {};
2021-07-31 14:33:18 +00:00
for (const message of messages) {
let recipient: string;
2021-07-31 14:33:18 +00:00
if (message.direction === Direction.Outbound) {
recipient = message.to;
2021-07-31 14:33:18 +00:00
} else {
recipient = message.from;
2021-07-31 14:33:18 +00:00
}
if (!conversations[recipient]) {
conversations[recipient] = [];
2021-07-31 14:33:18 +00:00
}
conversations[recipient]!.push({
...message,
content: decrypt(message.content, customer.encryptionKey),
});
2021-07-31 14:33:18 +00:00
conversations[recipient]!.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
2021-07-31 14:33:18 +00:00
}
conversations = Object.fromEntries(
Object.entries(conversations).sort(
2021-08-01 12:04:04 +00:00
([, a], [, b]) => b[b.length - 1]!.sentAt.getTime() - a[a.length - 1]!.sentAt.getTime(),
),
);
2021-07-31 14:33:18 +00:00
return conversations;
});