Optimized upsert... thanks Drizzle!

This commit is contained in:
Atridad Lahiji 2023-08-20 16:52:27 -06:00 committed by atridadl
parent 75fd34dc81
commit a88ee93426
No known key found for this signature in database
3 changed files with 14 additions and 19 deletions

View file

@ -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,

View file

@ -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`);

View file

@ -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),
};
}
);