findUnique from current user

Hi, I would like to get 1 entry by id, but only if the entry belongs to the current user. Is that possible with findUnique or do I have to use find findMany or findFirst? Example:
// Get a deposit by id from the current user
getById: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const deposit = await ctx.prisma.deposit.findFirst({
where: {
id: input.id,
userId: ctx.session.user.id,
},
});
return deposit;
}),
// Get a deposit by id from the current user
getById: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const deposit = await ctx.prisma.deposit.findFirst({
where: {
id: input.id,
userId: ctx.session.user.id,
},
});
return deposit;
}),
6 Replies
Ayato
Ayato2y ago
I think findFirst sounds fine, but it is getting worse, when we get to update or delete, because I would have to use deleteMany to put in multiple filter.
// Delete a deposit by id for the current user
delete: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const deposit = await ctx.prisma.deposit.deleteMany({
where: {
id: input.id,
userId: ctx.session.user.id,
},
});
return deposit;
}),
// Delete a deposit by id for the current user
delete: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const deposit = await ctx.prisma.deposit.deleteMany({
where: {
id: input.id,
userId: ctx.session.user.id,
},
});
return deposit;
}),
Abuzeid
Abuzeid2y ago
you can use delete it only deletes one, is the deposit id unique?
Diogo
Diogo2y ago
change deleteMany to delete
Ayato
Ayato2y ago
yes, but if another user gets the id he could delete it. Is that securety wise ok?
Diogo
Diogo2y ago
the only way for you to solve that, is to select the deposit by his id, get the userID returned on the response, check if it equal to the user logged in, and if yes delete else no something like this: // Get a deposit by id from the current user getById: protectedProcedure .input(z.object({ id: z.string() })) .query(async ({ ctx, input }) => { const deposit = await ctx.prisma.deposit.findFirst({ where: { id: input.id, }, })
if(deposit.userId == ctx.session.user.id){ const deposit = await ctx.prisma.deposit.delete({ where: { id: input.id, }, }); } else{ return ("Not your deposit.") } return ("Deleted")
}
}), note i dont know if its well written is just a sketch
Ayato
Ayato2y ago
I will take a look
Want results from more Discord servers?
Add your server