scott2breal
scott2breal
TTCTheo's Typesafe Cult
Created by scott2breal on 10/25/2022 in #questions
Connecting entities in Prisma
I'm attempting to connect two entities in prisma which share a many-to-many relationship. I have defined the relationship in my prisma schema as an implicit many-to-many relation. It works fine if the connection does not already exist, and prisma is smart enough to ON CONFLICT DO NOTHING when it finds the connection already exists. However, it does not throw an error when this happens. As an example, my code for the route in question looks something like this:
// studentRouter
enrollStudent: authedProcedure
.input(
z.object({
id: z.string().cuid(),
classId: z.string().cuid(),
})
)
.mutation(async ({ ctx, input }) => {
try {
return await ctx.prisma.student.update({
where: { id: input.id },
data: {
id: input.id,
classes: {
connect: { id: input.classId }
}
}
})
} catch (error) {
// No error is thrown, the mutation fails silently
console.log(error)
}
}),
// studentRouter
enrollStudent: authedProcedure
.input(
z.object({
id: z.string().cuid(),
classId: z.string().cuid(),
})
)
.mutation(async ({ ctx, input }) => {
try {
return await ctx.prisma.student.update({
where: { id: input.id },
data: {
id: input.id,
classes: {
connect: { id: input.classId }
}
}
})
} catch (error) {
// No error is thrown, the mutation fails silently
console.log(error)
}
}),
I would like to, in my trpc mutation, throw a new TRPCError when the user tries to create a connection which already exists in the database. However, I'm having trouble figuring out how to harness that prisma ON CONFLICT DO NOTHING behavior in my trpc route. I can get around this with an extra query and manually check for the existence of the connection, but it feels like there should be a better way. It's very possible I missed something (pretty new to all of this), but I've been scouring the prisma docs and I don't see this situation covered in the relevant reference or concept sections. Any help would be greatly appreciated!
1 replies