diff --git a/src/server/api/routers/room.ts b/src/server/api/routers/room.ts index 6508352..3868b2a 100644 --- a/src/server/api/routers/room.ts +++ b/src/server/api/routers/room.ts @@ -20,7 +20,7 @@ export const roomRouter = createTRPCRouter({ const room = await ctx.db .insert(rooms) .values({ - id: createId(), + id: `room_${createId()}`, userId: ctx.auth.userId, roomName: input.name, storyName: "First Story!", @@ -119,7 +119,7 @@ export const roomRouter = createTRPCRouter({ oldRoom && (await ctx.db.insert(logs).values({ - id: createId(), + id: `log_${createId()}`, userId: ctx.auth.userId, roomId: input.roomId, scale: oldRoom.scale, diff --git a/src/server/api/routers/vote.ts b/src/server/api/routers/vote.ts index f797c62..fa53e09 100644 --- a/src/server/api/routers/vote.ts +++ b/src/server/api/routers/vote.ts @@ -37,31 +37,24 @@ export const voteRouter = createTRPCRouter({ set: protectedProcedure .input(z.object({ value: z.string(), roomId: z.string() })) .mutation(async ({ ctx, input }) => { - const updateResult = await ctx.db - .update(votes) - .set({ + const upsertResult = await ctx.db + .insert(votes) + .values({ + id: `vote_${createId()}`, value: input.value, userId: ctx.auth.userId, roomId: input.roomId, }) - .where(eq(votes.userId, ctx.auth.userId)) - .returning(); - - let success = updateResult.length > 0; - - if (!success) { - const vote = await ctx.db - .insert(votes) - .values({ - id: createId(), + .onConflictDoUpdate({ + target: [votes.userId, votes.roomId], + set: { value: input.value, userId: ctx.auth.userId, roomId: input.roomId, - }) - .returning(); + }, + }); - success = vote.length > 0; - } + let success = upsertResult.rowCount > 0; if (success) { await invalidateCache(`kv_votecount`); diff --git a/src/server/schema.ts b/src/server/schema.ts index 8c6e4a2..34cecc5 100644 --- a/src/server/schema.ts +++ b/src/server/schema.ts @@ -5,6 +5,7 @@ import { boolean, json, index, + unique, } from "drizzle-orm/pg-core"; import { relations } from "drizzle-orm"; @@ -37,6 +38,7 @@ export const votes = pgTable( (table) => { return { userIdx: index("user_idx").on(table.userId), + unq: unique().on(table.userId, table.roomId), }; } );