A question on procedure design.
I would like to know if it is best to try combine procedures or keep them separated. I don't want to repeat myself but am not sure regarding best practices for this types of thing. Would appreciate if someone could push me in the right direction.
Something like this for bookmarks on 2 different post types
bookmarkPost: protectedProcedure
.input(
z.object({
postId: z.string(),
})
)
.mutation(async ({ ctx: { prisma, session }, input: { postId } }) => {
await prisma.bookMark.create({
data: {
userId: session.user.id,
postId,
},
});
}),
bookmarkTech: protectedProcedure
.input(
z.object({
techId: z.string(),
})
)
vs. combined
bookmarkItem: protectedProcedure
.input(
z
.object({
itemId: z.string(),
itemType: z.string().refine(value => ['post', 'tech', 'course'].includes(value), {
message: "Item type must be either 'post', 'tech', or 'course'",
}),
})
)
.mutation(async ({ ctx: { prisma, session }, input: { itemId, itemType } }) => {
switch(itemType) {
case 'post':
await prisma.bookMark.create({
data: {
userId: session.user.id,
postId: itemId,
},
});
break;
case 'tech':
await prisma.techBookMark.create({
data: {
userId: session.user.id,
techId: itemId,
},
});
break;
case 'course':
await prisma.courseBookMark.create({
data: {
userId: session.user.id,
courseId: itemId,
},
});
break;
default:
throw new Error("Invalid item type");
}
}),
3 Replies
Keep them separated. This is a question about the architecture of your code, which you want to keep "clean" because its easier to read and comprehend on the first pass (and thus, easier to modify in the future).
Once code is clean and working correctly you can do performance testing to find bottlenecks and degradations. Trying to predict the performance of your code is a vain effort. Avoid premature optimization. Focus on expressing how your code should behave in the simplest way possible. Make your job easier, not harder.
Thanks for that. I'll be careful going forward. I like to keep things separated but sometimes too much repetition like in this case i think would be best handled by combining them. i'm at quite a late stage of development on this current app so it's a good time to optimize. Made my components structure more reusable as well
I've already built out everything individually and now it's time to make these optimizations
You should combine the repeated code into functions so changes are localized to one location. If you have to make a change or fix a bug, it's easier to do correctly if you've separated the concerns.