Loro
Loro
TTCTheo's Typesafe Cult
Created by Loro on 4/25/2023 in #questions
How to perform additional validation on update mutation?
I want to protect each user's data so it can't be modified if you aren't the user who created the object (userId as foreign key). Here is my work in progress update mutation. I want to ensure that the object.userId matches the ctx.auth.userId before allowing to update it.
update: protectedProcedure
.input(
z.object({
id: z.string(),
name: z.string(),
description: z.string(),
value: z.number(),
userId: z.string(),
}))
.mutation(({ctx, input}) => {
return ctx.prisma.transaction.update({
where: { id: input.id },
data: { ...input, userId: ctx.auth.userId }
})
})
update: protectedProcedure
.input(
z.object({
id: z.string(),
name: z.string(),
description: z.string(),
value: z.number(),
userId: z.string(),
}))
.mutation(({ctx, input}) => {
return ctx.prisma.transaction.update({
where: { id: input.id },
data: { ...input, userId: ctx.auth.userId }
})
})
Since the above where only accepts id prop, I think I can add a find query before it and verify the userId matches ctx.prisma.transaction.update call
const found = ctx.prisma.transaction.findFirst({where: {id: input.id, userId: input.userId}});
if(!found) { throw new TRPCError({code:'UNAUTHORIZED"}); }
const found = ctx.prisma.transaction.findFirst({where: {id: input.id, userId: input.userId}});
if(!found) { throw new TRPCError({code:'UNAUTHORIZED"}); }
Does this make sense? Although from a db standpoint, these count as two separate db calls right?
7 replies