import { TRPCError } from "@trpc/server"; import type { CommittedMessage } from "../../types"; import { router, createCallerFactory, authProcedure } from "./server"; import { z } from "zod"; const authConversationProcedure = authProcedure .input(z.object({ id: z.string() })) .use(async ({ input: { id }, ctx: { dbClient, jwt }, next }) => { const rows = await dbClient .selectFrom("conversations") .selectAll() .where("id", "=", id) .execute(); if (rows[0].userId !== jwt.id) { throw new TRPCError({ code: "UNAUTHORIZED" }); } return next({ ctx: { conversationRow: rows[0], }, }); }); export const conversations = router({ fetchAll: authProcedure.query(async ({ ctx: { dbClient, jwt } }) => { const rows = await dbClient .selectFrom("conversations") .where("userId", "=", jwt.id as string) .selectAll() .execute(); return rows; }), fetchOne: authConversationProcedure.query( async ({ ctx: { conversationRow } }) => { return conversationRow; } ), start: authProcedure.mutation(async ({ ctx: { dbClient, jwt } }) => { const insertedRows = await dbClient .insertInto("conversations") .values({ title: "New Conversation", userId: jwt?.id as string, }) .returningAll() .execute(); return insertedRows[0]; }), deleteOne: authConversationProcedure.mutation( async ({ input: { id }, ctx: { dbClient, jwt } }) => { await dbClient .deleteFrom("conversations") .where("id", "=", id) .where("userId", "=", jwt.id as string) .execute(); return { ok: true }; } ), updateTitle: authConversationProcedure .input( z.object({ title: z.string(), }) ) .mutation(async ({ input: { id, title }, ctx: { dbClient, jwt } }) => { await dbClient .updateTable("conversations") .set({ title }) .where("id", "=", id) .where("userId", "=", jwt.id as string) .execute(); return { ok: true }; }), fetchMessages: authProcedure .input(z.object({ conversationId: z.string() })) .query(async ({ input: { conversationId }, ctx: { dbClient, jwt } }) => { const rows = await dbClient .selectFrom("messages") .innerJoin( "conversations", "conversations.id", "messages.conversationId" ) .selectAll("messages") .where("conversationId", "=", conversationId) .where("conversations.userId", "=", jwt.id as string) .execute(); return rows as Array; }), }); export const createCaller = createCallerFactory(conversations);