Optimized upsert... thanks Drizzle!
This commit is contained in:
parent
75fd34dc81
commit
a88ee93426
3 changed files with 14 additions and 19 deletions
|
@ -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,
|
||||
|
|
|
@ -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`);
|
||||
|
|
|
@ -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),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
|
Loading…
Add table
Reference in a new issue